[英]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.您的上述代码存在三个问题。
=
, you must do it using the setter functions.=
直接为 state 变量赋值,您必须使用 setter 函数来完成。useEffect
.useEffect
中添加依赖项列表。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
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
localStorage.setItem("value", value);
localStorage.setItem("value", value);
const localStorageValue = localStorage.getItem("value");
const localStorageValue = localStorage.getItem("value");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.