ReactJS-刷新页面后,LocalStorage未更新
我在这里是新手,有人可以帮助我解决这个问题。为什么我在redux上的局部存储在我尝试从Cartitem中删除状态后没有更新?因此,每次我卸下购物车时,我都会刷新.. LocalStorage不会返回新值。有人可以帮我解释一下吗?请帮助
cartslice.js
export const cartRemove = createAsyncThunk(
'cartRemove/remove',
async (id, thunkAPI) => {
try {
const res = await axios.get(`http://localhost:8000/api/products/${id}`);
const data = await res.data;
console.log(data._id);
thunkAPI.dispatch(removeCart(data._id));
return localStorage.setItem(
'cartItems',
JSON.stringify(thunkAPI.getState().cart.cartItems)
);
} catch (error) {}
}
);
const cartSlice = createSlice({
name: 'cart',
initialState: {
cartItems: localStorage.getItem('cartItems')
? JSON.parse(localStorage.getItem('cartItems'))
: [],
},
reducers: {
removeCart: (state, action) => {
return {
...state,
cartItems: state.cartItems.filter(
(elem) => elem.product !== action.payload
),
};
},
export default cartSlice.reducer;
export const { addCart, removeCart } = cartSlice.actions;
cartscreen.jsx
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Link, useNavigate } from 'react-router-dom';
import { useLocation, useParams } from 'react-router-dom';
import Message from '../components/Message';
import { addToCart, cartRemove, removeCart } from '../redux/cartSlice';
const CartScreen = () => {
const dispatch = useDispatch();
const { cartItems } = useSelector((state) => state.cart);
const { id } = useParams();
const navigate = useNavigate();
let qty = useLocation().search;
qty = qty ? qty.split('=')[1] * 1 : 1;
useEffect(() => {
if (id) {
dispatch(addToCart({ id, qty }));
}
}, [dispatch, qty, id]);
const removeFromCartHandler = (id) => {
dispatch(cartRemove(id));
};
im new here, can somebody help me to solve this. why my localstorage on my redux did not update after i try to remove the state from cartItems? so everytime i remove the cart, and i refresh.. localstorage did not return the new value. can somebody help me and explain this? pls help
cartSlice.js
export const cartRemove = createAsyncThunk(
'cartRemove/remove',
async (id, thunkAPI) => {
try {
const res = await axios.get(`http://localhost:8000/api/products/${id}`);
const data = await res.data;
console.log(data._id);
thunkAPI.dispatch(removeCart(data._id));
return localStorage.setItem(
'cartItems',
JSON.stringify(thunkAPI.getState().cart.cartItems)
);
} catch (error) {}
}
);
const cartSlice = createSlice({
name: 'cart',
initialState: {
cartItems: localStorage.getItem('cartItems')
? JSON.parse(localStorage.getItem('cartItems'))
: [],
},
reducers: {
removeCart: (state, action) => {
return {
...state,
cartItems: state.cartItems.filter(
(elem) => elem.product !== action.payload
),
};
},
export default cartSlice.reducer;
export const { addCart, removeCart } = cartSlice.actions;
cartScreen.jsx
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Link, useNavigate } from 'react-router-dom';
import { useLocation, useParams } from 'react-router-dom';
import Message from '../components/Message';
import { addToCart, cartRemove, removeCart } from '../redux/cartSlice';
const CartScreen = () => {
const dispatch = useDispatch();
const { cartItems } = useSelector((state) => state.cart);
const { id } = useParams();
const navigate = useNavigate();
let qty = useLocation().search;
qty = qty ? qty.split('=')[1] * 1 : 1;
useEffect(() => {
if (id) {
dispatch(addToCart({ id, qty }));
}
}, [dispatch, qty, id]);
const removeFromCartHandler = (id) => {
dispatch(cartRemove(id));
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题在您的thunk中,在这部分中:
您基本上是在尝试更新redux状态,并在访问该新状态之后立即更新,但是
thunkapi.getState()。cart.cartitems
,而不是新的(正如您所期望的那样),而不是新状态,而不是新状态。解决方案是在removecart Slicer还原器中移动本地存储设置器,或者如果您想坚持使用当前的解决方案,则可以执行类似的操作:Problem is in your thunk, in this part:
You are basically trying to update redux state and immediately after to access that new state, but
thunkAPI.getState().cart.cartItems
returns old state, from closure, instead of new one(as you were expecting), and thats why you always update local storage with old, instead with new state. Solution would be to move local storage setter in removeCart slicer reducer, or if you wish to stick with the current solution, to do something like: