【问题标题】:Saving array to local storage (reactjs)将数组保存到本地存储(reactjs)
【发布时间】:2020-08-20 16:40:42
【问题描述】:

我正在尝试将产品从购物车保存到本地存储,但在页面刷新时它并没有像想象的那样工作。当我刷新页面时,产品在购物车中,但一旦我添加新项目,它就会被删除。此外,删除产品会删除所有内容,而不是使用本地存储时的特定内容。这是我尝试过的:

App.tsx设置数组中

const [productList, dispatch] = useReducer((state: any, action: any) => {
    switch (action.type) {
      case "ADD_ITEM":
        const noDoubleItems = state.filter((item: any) => item.id !== action.payload.id);
        localStorage.setItem("cart",JSON.stringify([...noDoubleItems, action.payload]));
        return [...noDoubleItems, action.payload];

      case "DELETE_ITEM":
        localStorage.setItem("cart", JSON.stringify(state));
        return state.filter((item: any) => item.id !== action.payload.id);

      default:
        return state;
    }
  }, []);

Cart.tsx 中获取数组

  const storageCart = localStorage.getItem("cart");
  const storageCartObject = storageCart && JSON.parse(storageCart);

这里是代码沙箱:https://codesandbox.io/s/flamboyant-torvalds-tevby?file=/src/components/pages/Cart.tsx:298-1026

【问题讨论】:

  • 你在使用 Redux 吗?
  • Reducer 函数(在 redux 或其他普通反应中)should really be pure functions,这意味着它们返回一个新状态并且没有其他副作用。写入本地存储是一个副作用。

标签: reactjs local-storage


【解决方案1】:

您的 storageCart 已使用 localStorage 初始化,但您的 Redux 状态未初始化。所以, storageCart 仍然存在,但是当您发送 ADD_ITEM 操作时,Store 是空的,这就是您添加的第一个产品消失的原因。

您也可以在每次用户刷新页面时使用 redux-persist 来持久化 Redux 存储。所以你不需要处理所有本地存储的东西。

【讨论】:

  • 谢谢!我必须安装npm install use-persisted-reducer --save,创建像const usePersistedReducer = createPersistedReducer('state') 这样的持久化reducer,然后用usePersistedReducer 替换useReduer,就这么简单!
猜你喜欢
  • 1970-01-01
  • 2014-07-07
  • 1970-01-01
  • 2018-11-05
  • 2016-04-29
  • 2018-11-17
  • 2019-01-03
  • 1970-01-01
相关资源
最近更新 更多