页面刷新后本地存储重置为默认值
大家好,最近我正在使用 ReactJS 构建添加到购物车功能,因为我没有后端服务器来存储客户购物车,所以我将其存储在 localstorage 中。当我单击添加到购物车时,该项目被设置到本地存储中,但是刷新页面后,cartItems 值被设置为默认值。
export const Store = createContext();
const initialState = {
cart: {
cartItems :[]
},
};
export function StoreProvider(props) {
const [items, setItems] = useLocalStorage('cartItems', []);
const [state, dispatch] = useReducer(reducer, initialState);
useEffect(() => {
setItems(state.cart.cartItems);
}, [setItems,state.cart.cartItems]);
const value = { state, dispatch };
return (<Store.Provider value={value}>{props.children}</Store.Provider>);
}
function reducer(state, action) {
switch (action.type) {
case 'ADD_TO_CART': {
const newItem = action.payload;
const existItem = state.cart.cartItems.find(
(item) => item.id === newItem.id
);
const cartItems = existItem
? state.cart.cartItems.map((item) =>
item.id === existItem.id ? newItem : item
)
: [...state.cart.cartItems, newItem];
...
Hi guys recently i am using reactjs to build add to cart function, because I don't have backend server to store customer cart so I store it at localstorage . When i click add to cart the item is being set into the localstorage , However after refreshing the page, cartItems value being set to default.
export const Store = createContext();
const initialState = {
cart: {
cartItems :[]
},
};
export function StoreProvider(props) {
const [items, setItems] = useLocalStorage('cartItems', []);
const [state, dispatch] = useReducer(reducer, initialState);
useEffect(() => {
setItems(state.cart.cartItems);
}, [setItems,state.cart.cartItems]);
const value = { state, dispatch };
return (<Store.Provider value={value}>{props.children}</Store.Provider>);
}
function reducer(state, action) {
switch (action.type) {
case 'ADD_TO_CART': {
const newItem = action.payload;
const existItem = state.cart.cartItems.find(
(item) => item.id === newItem.id
);
const cartItems = existItem
? state.cart.cartItems.map((item) =>
item.id === existItem.id ? newItem : item
)
: [...state.cart.cartItems, newItem];
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当此元素在刷新后呈现时,您的
useEffect()
将运行。第一次运行 useEffect 时,它将项目设置为状态中最初的值(空数组)。您应该能够通过在第一次渲染时跳过项目更新来解决此问题,这可以通过在ref
中存储标志来完成。像这样的东西:When this element renders after a refresh, your
useEffect()
will run. The first time the useEffect is run, it is setting the items to the value initially in the state (an empty array). You should be able to solve this problem by skipping the items update on the first render, and this can be accomplished by storing a flag in aref
. Something like: