如何让 useEffect 监听 localStorage 中的任何变化?

时间:2021-05-25 07:37:37

标签: javascript reactjs

我正在尝试让我的 React 应用程序从 localStorage 获取对象的 todos 数组并将其提供给 setTodos。为此,我需要有一个 useEffect 来监听本地存储中发生的任何更改,所以我就是这样做的:

  useEffect(() => {
      if(localStorage.getItem('todos')) {
        const todos = JSON.parse(localStorage.getItem('todos'))
        setTodos(todos);
      }
  }, [ window.addEventListener('storage', () => {})]);

问题是每次我从 localStorage 中添加或删除某些东西时都不会触发 useEffect。 这是让 useEffect 监听 localStorage 的错误方式吗?

我尝试了解决方案 explained here 但它对我不起作用,我真诚地不明白为什么它应该起作用,因为侦听器没有作为 useEffect 中的第二个参数传递

1 个答案:

答案 0 :(得分:4)

您不能以这种方式重新运行 useEffect 回调,但您可以设置事件处理程序并让它重新加载 todos,请参阅评论:

useEffect(() => {
    // Load the todos on mount
    const todosString = localStorage.getItem("todos");
    if (todosString) {
        const todos = JSON.parse(todosString);
        setTodos(todos);
    }
    // Respond to the `storage` event
    function storageEventHandler(event) {
        if (event.key === "todos") {
            const todos = JSON.parse(event.newValue);
            setTodos(todos);
        }
    }
    // Hook up the event handler
    window.addEventListener("storage", storageEventHandler);
    return () => {
        // Remove the handler when the component unmounts
        window.removeEventListener("storage", storageEventHandler);
    };
}, []);

请注意,storage event 仅在存储通过不同窗口中的代码更改为当前窗口时发生。如果您在同一窗口中更改 todos,则必须手动触发。