【问题标题】:How to use localStorage with useReducer hook?如何将 localStorage 与 useReducer 挂钩使用?
【发布时间】:2022-01-10 20:44:25
【问题描述】:

我有一个使用 useReducer 创建的待办事项应用程序,我需要将它们保存到 localStorage,但出现错误。这里可能有什么问题?

const [{ todos, todoCount }, dispatch] = useReducer(
    reducer,
    {
      todos: [],
      todoCount: 0
    },
    (initial) => JSON.parse(localStorage.getItem("todos")) || initial
  );
 
  useEffect(() => {
    localStorage.setItem("todos", JSON.stringify(todos));
  }, [todos]);

我收到此错误: 引发了跨域错误。 React 无法访问开发中的实际错误对象。请参阅https://reactjs.org/link/crossorigin-error 了解更多信息。

当我使用 useReducer 编写一个简单的计数器应用程序时,我以与此相同的方式保存到 localStorage,但使用 todo 它不起作用

【问题讨论】:

  • 你遇到了什么错误?
  • 请同时发布错误信息。是什么让你对它的内容想得如此之少以至于你干脆忽略它?

标签: reactjs react-hooks local-storage use-reducer


【解决方案1】:

需要使用useContext+useReducer+localStorage:

 const initialState = {
    todos:
      localStorage.getItem("todos") == null
        ? []
        : JSON.parse(localStorage.getItem("todos"))
  };
  const [{ todos }, dispatch] = useReducer(
    reducer,
    /* {
      todos: [],
      todoCount: 0
    }*/
    initialState
  );
  useEffect(() => {
    localStorage.setItem("todos", JSON.stringify(todos));
  }, [todos]);

【讨论】:

    猜你喜欢
    • 2019-12-02
    • 2021-10-01
    • 2023-03-07
    • 2020-04-04
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 2021-02-13
    相关资源
    最近更新 更多