【发布时间】:2020-12-22 04:23:57
【问题描述】:
我正在使用 redux 并且有简单的问题。 redux 更新状态后如何进行操作。例如我有这个代码。
import {
ADD_TO_CART,
ADD_QUANTITY,
SUB_QUANTITY,
REMOVE_FROM_CART,
EMPTY_CART,
UPDATE_PRICE
} from '../actions/actions-types/aside-actions'
let cartInStorage = localStorage.getItem('cart')
let cartInStorageObject = JSON.parse(cartInStorage)
const initialState = {
cart: cartInStorageObject || [],
totalPrice: 0
}
export default function asideReducer(state = initialState, action) {
let cart = state.cart
let cartStringify = JSON.stringify(cart)
localStorage.setItem('cart', cartStringify)
switch (action.type) {
case ADD_TO_CART:
let itemInCart = cart.find(item => item.product._id == action.payload.product._id)
return{
...state // Example return
}
default:
return state
}
}
我需要保存到本地存储日期到购物车,但函数 localstorage.setItem 在操作之前并且在本地存储中不保存最后状态。 如何仅保存到本地存储 redux 上次状态更新? 非常感谢
【问题讨论】:
-
这可能是 redux 中间件的好案例
标签: redux react-redux