简体   繁体   English

在 ReactJS 中尝试使用 useEffect() 从本地存储获取数据时出现本地存储问题

[英]local storage problem when trying to fetch data from localstorage using useEffect() in ReactJS

I am trying to fetch data in localstorage using ReactJS. Can some one please help me here is my sample code.我正在尝试使用 ReactJS 在 localstorage 中获取数据。有人可以帮助我吗?这是我的示例代码。


let [rows,setRows] = useState([]);

    React.useEffect(() => {
        rows = localStorage.getItem("my_tier_list");
        if(rows){
            setRows(JSON.parse(rows));
        }
  
      },[]);
  
      React.useEffect(() => {
        localStorage.setItem("my_tier_list", JSON.stringify(cart));
      });

Can some one please help me and thanks in advance有人可以帮我吗,在此先感谢

There are three problems to your above code.您的上述代码存在三个问题。

  1. You can't directly assign values to your state variable using = , you must do it using the setter functions.您不能使用=直接为 state 变量赋值,您必须使用 setter 函数来完成。
  2. You have not added the dependency list in the second useEffect .您尚未在第二个useEffect中添加依赖项列表。
  3. You have not used the correct name to set the localStorage.您没有使用正确的名称来设置 localStorage。
let [rows,setRows] = useState([]);

    React.useEffect(() => {
        // you can't directly set a state variable. Create a new local variable
        const localRows = localStorage.getItem("my_tier_list");
        if(localRows){
            setRows(JSON.parse(localRows));
        }
  
      },[]);
  
      React.useEffect(() => {
        localStorage.setItem("my_tier_list", JSON.stringify(rows)); // corrected it to rows
      }, [rows]); // added the array as dependency list. This will trigger this only when "rows" gets changed

Update更新

Based on your code shared through code sandbox, you need to update your Reducer.js.根据通过代码沙箱共享的代码,您需要更新 Reducer.js。

const updateLocalStorage = (cart) => {
  localStorage.setItem("my_tier_list", JSON.stringify(cart));
};
export const cartReducer = (state, action) => {
  switch (action.type) {
    case "ADD_TO_CART": {
      const updatedState = {
        ...state,
        cart: [...state.cart, { ...action.payload, qty: 1 }]
      };
      updateLocalStorage(updatedState.cart);
      return updatedState;
    }
    case "REMOVE_FROM_CART": {
      const updatedState = {
        ...state,
        cart: state.cart.filter((c) => c.id !== action.payload.id)
      };
      updateLocalStorage(updatedState.cart);
      return updatedState;
    }
    case "CHANGE_CART_QTY": {
      const updatedState = {
        ...state,
        cart: state.cart.filter((c) =>
          c.id === action.payload.id ? (c.qty = action.payload.qty) : c.qty
        )
      };
      updateLocalStorage(updatedState.cart);
      return updatedState;
    }
    default:
      return state;
  }
};

And in Header.js而在 Header.js

    let [rows,setRows] = useState([]);

    React.useEffect(() => {
        const localRows = localStorage.getItem("my_tier_list");
        if(localRows){
            setRows(JSON.parse(localRows));
        }
      },[cart]); // adding cart will ensure any changes you make is reflected.

Please look into following sandbox: https://codesandbox.io/s/heuristic-rain-n97hf3请查看以下沙箱: https://codesandbox.io/s/heuristic-rain-n97hf3

  • Set local storage item on some event handler: localStorage.setItem("value", value);在某些事件处理程序上设置本地存储项: localStorage.setItem("value", value);
  • Get local storage item with: const localStorageValue = localStorage.getItem("value");获取本地存储项: const localStorageValue = localStorage.getItem("value");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM