reactjs - 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);
}
}
});
解决方案
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 += 1
x.value = 0
map()
Immer
forEach
推荐阅读
- javascript - 对象对象是什么意思
- python - 如何使用 Pandas 读取镶木地板文件
- python - 如何生成满足某些约束的初始值
- django - 我在相关领域没有得到明显的结果
- perl - apache DocumentRoot 可以更改 perl @INC 吗?
- c# - 有没有一种方法可以将光线投射击中的对象与另一个游戏对象进行比较?
- laravel - 我在将 Laravel 项目部署到服务器中的子域时遇到问题
- c# - 客户端和oracle服务器之间的重音字符编码问题
- intellij-idea - 如何调试 npm 应用程序
- angular - 如何在 ngContainer 中使用变量