Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么刷新页面时会删除本地存储?_Javascript_Reactjs_Local Storage - Fatal编程技术网

Javascript 为什么刷新页面时会删除本地存储?

Javascript 为什么刷新页面时会删除本地存储?,javascript,reactjs,local-storage,Javascript,Reactjs,Local Storage,我在上下文API中有一个状态管理的缩减器。我正在保存我的TODO,它正在成功执行,但当ı刷新页面时,所有TODO都将被删除,并且只保留空数组 // The relevant part in the reducer. case "TODO_ADD_USER": return { ...state, users: action.payload, }; 您的代码有几个问题 这里最大的一个问题是,你在拿到TODO之前先保存TO

我在上下文API中有一个状态管理的缩减器。我正在保存我的TODO,它正在成功执行,但当ı刷新页面时,所有TODO都将被删除,并且只保留空数组

// The relevant part in the reducer.
case "TODO_ADD_USER":
      return {
        ...state,
        users: action.payload,
      };

您的代码有几个问题

这里最大的一个问题是,你在拿到TODO之前先保存TODO。因此,在应用程序开始时,事情会被重置,这是有问题的

接下来,你们的储蓄条件有点倒退。您希望检查state.users===null是否为空,并为此执行特殊操作,而不是检查localStorage.getItem(“用户”)==null,因为默认情况下该值为空,与内存中的值无关

事实上,如果localStorage值不是null,但是
state.users
是null,那么它会将
“null”
设置为localStorage,这不太理想

以下是工作代码:

  useEffect(() => {
    // Get the item from local storage. JSON.parse(null) returns null rather than throws
    // Get from local storage before setting it
    const localTodos = JSON.parse(localStorage.getItem("users")) || [];
    dispatch({ type: "TODO_ADD_USER", payload: localTodos });
  }, []);

  useEffect(() => {
    // The conditions for this was wrong.
    // You want to check if `state.users` has a value
    // If it does, store! If not, don't store.
    // That way you don't reset data
    // In the case that you have this app running in two windows,
    // there's more that needs to be done for that.
    if (state.users) {
      localStorage.setItem("users", JSON.stringify(state.users || []));
    }
  }, [state]);

Place of keeping the state.
const users = {
  users: [],
};
  useEffect(() => {
    // Get the item from local storage. JSON.parse(null) returns null rather than throws
    // Get from local storage before setting it
    const localTodos = JSON.parse(localStorage.getItem("users")) || [];
    dispatch({ type: "TODO_ADD_USER", payload: localTodos });
  }, []);

  useEffect(() => {
    // The conditions for this was wrong.
    // You want to check if `state.users` has a value
    // If it does, store! If not, don't store.
    // That way you don't reset data
    // In the case that you have this app running in two windows,
    // there's more that needs to be done for that.
    if (state.users) {
      localStorage.setItem("users", JSON.stringify(state.users || []));
    }
  }, [state]);