首页 > 解决方案 > Redux Toolkit:state.filter 未更改 state 而 state.map 更改

问题描述

我有一个计数器列表,如 initialState. 我的所有其他功能slice都在工作,除了deleteCounter. 我已经确认派送工作正常。

export const myCounterSlice = createSlice({
  name: 'myCounter',
  initialState: [
    { id: 1, value: 4 },
    { id: 2, value: 5 },
    { id: 3, value: 8 },
    { id: 4, value: 2 }
  ],
  reducers: {
    incrementCount: (state, action) => {
      state.map(x => x.id === action.payload ? x.value += 1 : x);
    },
    resetCount: (state, action) => {
      state.map(x => x.id === action.payload ? x.value = 0 : x);
    },
    deleteCounter: (state, action) => {
      state.filter(x => x.id != action.payload)
    },
    resetAllCount: (state) => {
      state.map(x => x.value = 0);
    }
  }
});

标签: reactjsreduxredux-toolkit

解决方案


Immer 的工作原理是跟踪对现有代理包装值的突变,或者让您返回一个新的状态值:

https://redux-toolkit.js.org/usage/immer-reducers#mutating-and-returning-state

你的代码没有做这些。.filter()函数返回一个新数组。因为 reducer 函数上有花括号,所以必须使用return关键字来实际返回一些新的状态值。因此,您需要让return state.filter()Immer 看到这些更新中的任何一个。

另一方面,您的调用实际上是用and.map()改变它循环的项目。对于 map() 函数来说,这通常是一件坏事——永远不应该用来改变值,进出. 从概念上讲,这是错误的方法。如果您想在循环中编写变异代码,请使用以便其他程序员知道会发生什么。x.value += 1x.value = 0map()ImmerforEach


推荐阅读