如何使用 redux 工具包从 redux 状态的数组中删除单个元素

How can I delet a single element from the array in redux state using redux toolkit

我正在使用 redux-toolkit 库中的 createSlice() 函数在数组中添加和删除项目。

addProject reducer 函数工作正常但 removeRpoject 不起作用。

//projects.js

import { createSlice } from "@reduxjs/toolkit";

let lastId = 0;

const slice = createSlice({
  name: "projects",
  initialState: [],
  reducers: {
    projectAdded: (projects, action) => {
      projects.push({
        id: ++lastId,
        name: action.payload.name,
      });
    },
    projectRemoved: (projects, action) =>
      (projects = projects.filter((pro) => pro.id !== action.payload.id)),
  },
});
export const { projectAdded, projectRemoved } = slice.actions;
export default slice.reducer;

//store.js

import { configureStore } from "@reduxjs/toolkit";
import reducer from "./projects";
const store = configureStore({ reducer: reducer });

export default store;

//index.js

import store from "./store/store";
import { projectAdded, projectRemoved } from "./store/projects";
const unsubscribe = store.subscribe(() => {
  console.log("store Changed", store.getState());
});
store.dispatch(projectAdded({ name: "Project 1" }));
store.dispatch(projectRemoved({ id: 1 }));

您正在替换状态的根对象 (projects) - 这会终止 immer 更改检测。

最简单的方法是只 return 过滤后的数组,而不先将其分配给草稿对象:

projectRemoved: (projects, action) => projects.filter((pro) => pro.id !== action.payload.id),

另请参阅: https://immerjs.github.io/immer/docs/update-patterns#array-mutations