【问题标题】:local storage data resets after refreshing page刷新页面后本地存储数据重置
【发布时间】:2021-08-09 21:11:43
【问题描述】:

我正在尝试为我的网站制作购物车页面。在我更改产品数量时从产品页面添加产品或在购物车页面前端删除产品后效果很好,更改也反映在本地存储中,但刷新页面后数量重置为默认值。但是,在访问任何其他页面然后返回购物车页面后,所有功能都可以正常工作。 我正在使用此代码:

localStorage.setItem('cartItems', JSON.stringify(getState().cart.cartItems))

这是代码剩余代码

import axios from 'axios'
import { CART_ADD_ITEM, CART_REMOVE_ITEM } from '../constants/cartConstants'

export const addToCart = (id, qty) => async (dispatch, getState) => {
  const { data } = await axios.get(`/api/products/${id}`)

  dispatch({
    type: CART_ADD_ITEM,
    payload: {
      product: data._id,
      name: data.name,
      image: data.image,
      price: data.price,
      countInStock: data.countInStock,
      qty,
    },
  })

  localStorage.setItem('cartItems', JSON.stringify(getState().cart.cartItems))
}

export const removeFromCart = (id) => (dispatch, getState) => {
  dispatch({
    type: CART_REMOVE_ITEM,
    payload: id,
  })

  localStorage.setItem('cartItems', JSON.stringify(getState().cart.cartItems))
}

【问题讨论】:

  • 添加更多代码。你在哪里使用localStorage.removeItem?
  • 我没有在任何地方使用过localStorage.removeItem
  • 在localStorage.setItem()之前尝试console.log() getState().cart每个@
  • 能否再添加一些代码?似乎您在每次刷新时都将默认值存储在 localStorage 中。

标签: node.js reactjs mern


【解决方案1】:

当页面刷新时,在你代码的任何地方,yoy应该使用localStorage.getItem来获取之前用localStorage.setItem保存在存储中的数据,用JSON.parse解析它,然后在redux状态下分发解析后的cartItems数组使用新操作(例如 CART_SAVE_ALL_ITEMS)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多