我正在练习Redux,在我的项目中,当我调度一个动作时,我会在开发工具中看到,但状态不会改变,它将仍然是一个空数组。为什么会发生这种情况?我将感激你的一点帮助
购物cart.js
import { createSlice, createAction } from "@reduxjs/toolkit";
// Action Creator
export const itemAdd = createAction("products/itemAdded");
const slice = createSlice({
name: "shoppingCart",
initialState: [],
reducers: {
itemAdded: (cart, action) => cart.push(action.payload),
},
});
export const { itemAdded} = slice.actions;
export default slice.reducer;
调度
import { useDispatch, useSelector } from "react-redux";
import { itemAdd } from "../../store/state/shoppingCart";
// It's an onClick Event Handler
const handleAddItem = (item) => {
dispatch(itemAdd(item));
};
另外,您的reducer需要大括号。
itemAdded: (cart, action) => { cart.push(action.payload) }
否则,它将返回cart.push
的返回值,即数组的新长度,如果您修改状态并同时返回不相关的内容,immer
将无法完成其工作。
因为您正在导入itemAdd
import { itemAdd } from "../../store/state/shoppingCart";
代替itemAdded
import { itemAdded } from "../../store/state/shoppingCart";