📜  react 中的响应式本地存储 - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:02:04.096000             🧑  作者: Mango

代码示例1
function useStorageWatcher(key) {
  const [val, setVal] = useState(localStorage.get(key));

  useEffect(() => {
    const handler = () => val !== localStorage.get(key) && setVal(localStorage.get(key));
    window.addEventListener("storage", handle);
    () => window.removeEventListener("storage", handler);
  }, []);

  useEffect(() => {
    setVal(localStorage.get(key));
  }, [key]);

  return val;

}