ReactJS-刷新页面后,LocalStorage未更新

发布于 2025-02-10 23:10:26 字数 2000 浏览 1 评论 0原文

我在这里是新手,有人可以帮助我解决这个问题。为什么我在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

椵侞 2025-02-17 23:10:26

问题在您的thunk中,在这部分中:

thunkAPI.dispatch(removeCart(data._id));
return localStorage.setItem(
    'cartItems',
    JSON.stringify(thunkAPI.getState().cart.cartItems)
  )

您基本上是在尝试更新redux状态,并在访问该新状态之后立即更新,但是thunkapi.getState()。cart.cartitems ,而不是新的(正如您所期望的那样),而不是新状态,而不是新状态。解决方案是在removecart Slicer还原器中移动本地存储设置器,或者如果您想坚持使用当前的解决方案,则可以执行类似的操作:

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));
      const updatedCart = thunkAPI.getState().cart.cartItems.filter(i => i.product !== data._id);
      return localStorage.setItem(
        'cartItems',
        JSON.stringify(updatedCart)
      );
    } catch (error) {}
  }
);

Problem is in your thunk, in this part:

thunkAPI.dispatch(removeCart(data._id));
return localStorage.setItem(
    'cartItems',
    JSON.stringify(thunkAPI.getState().cart.cartItems)
  )

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:

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));
      const updatedCart = thunkAPI.getState().cart.cartItems.filter(i => i.product !== data._id);
      return localStorage.setItem(
        'cartItems',
        JSON.stringify(updatedCart)
      );
    } catch (error) {}
  }
);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文