为什么刷新页面时localStorage值为空?

问题描述 投票:0回答:1

我正在使用

Context API
将购物车数据传递到不同的页面,并尝试使用
localStorage
在刷新页面时设置和检索购物车数据。

每次更改

localStorage
后将购物车数据设置为
state
工作正常,但问题是当页面刷新时,
localStorage
的数据消失了,因此购物车数据将被重置!

我不明白我在哪里做错了以及为什么刷新页面时不会设置和使用

localStorage
数据。你能帮我解决这个问题吗? (出于显示目的,我现在只是
log
调整
localStorage
值。)

这是我的代码:

function CartProvider({ children }: Props) {
  const [state, dispatch] = useReducer(reducer, initialState);

  const [retrievedState, setRetrievedState] = useState(
    JSON.parse(localStorage.getItem("cart") || "") || initialState
  );

  useEffect(() => {
    localStorage.setItem("cart", JSON.stringify(state));
    setRetrievedState(state);
  }, [state]);

  console.log(retrievedState);

  return (
    <CartContext.Provider value={{ state, dispatch }}>
      {children}
    </CartContext.Provider>
  );
}
reactjs react-hooks local-storage react-context
1个回答
0
投票

您正在 useState 挂钩中初始化retrieveState。问题是,当 localStorage 中没有数据时,您试图解析空字符串 ("")。这会导致解析错误,导致retrievedState被设置为null。尝试这样的事情,

function CartProvider({ children }: Props) {
  const [state, dispatch] = useReducer(reducer, initialState);

  // retrieve data from localStorage, or use initialState if localStorage is empty
  const [retrievedState, setRetrievedState] = useState(
    JSON.parse(localStorage.getItem("cart")) || initialState
  );

  useEffect(() => {
    // update localStorage whenever the state changes
    localStorage.setItem("cart", JSON.stringify(state));
    setRetrievedState(state);
  }, [state]);

  console.log(retrievedState);

  return (
    <CartContext.Provider value={{ state, dispatch }}>
      {children}
    </CartContext.Provider>
  );
}

这应该确保只有当 localStorage 中没有数据时,retrievedState 才会被设置为 null,否则,它将被设置为解析的数据。这应该可以防止解析错误并确保您的购物车数据在页面刷新后仍然存在。

© www.soinside.com 2019 - 2024. All rights reserved.