Redux 工具包:state.filter 不更改状态而 state.map 更改状态

Redux Toolkit: state.filter not making changes to state while state.map does

我有一个在 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);
    }
  }
});

Immer 的工作方式是跟踪 突变 到现有的 Proxy-wrapped 值,或者让您 return 一个新的状态值:

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

您的代码没有执行这些操作。 .filter() 函数 returns 一个新数组。因为你在 reducer 函数上有大括号,所以你必须使用 return 关键字来实际 return 一些新的状态值。因此,您需要为 Immer 执行 return state.filter() 才能看到任何这些更新。

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