gpt4 book ai didi

javascript - 如何在 redux reducer 中改变状态数组?

转载 作者:行者123 更新时间:2023-11-30 20:14:27 27 4
gpt4 key购买 nike

更改前的状态如下所示:

foreignBases: [
{
base: {
id: "5b8125ec14bb4f35f8f01aa9",
...
},
baseuser: {
userId: "tester1",
...
}
},
{ base: { ... }, baseuser: { ... } }
]

通过调度,用户将 baseuser 键中的 bool 值更改为 true,reducer 然后应该更新这个特定键值对的状态,但我可以似乎用这个做对了:

for (let i = 0; i < state.foreignBases.length; i++) {
if (action.baseUser.created === state.foreignBases[i].baseuser.created) {
return Object.assign({}, state, {
foreignBases: [
...state.foreignBases,
{
base: { ...state.foreignBases[i].base },
baseuser: action.baseUser
}
]
});
}

这只是在状态中添加了另一个对象,而我真的只需要替换一个对象中的 baseuser 的一个 bool 值

最佳答案

请务必在下方查看更新。

扩展运算符正在重新插入整个 foreignBases,然后您要添加另一个对象,我认为这是您的预期突变。

我想你的意思是这样的(未经测试)

for (let i = 0; i < state.foreignBases.length; i++) {
if (action.baseUser.created === state.foreignBases[i].baseuser.created) {
let foreignBases = [...state.foreignBases];
foreignBases[i].baseuser = action.baseUser;
return Object.assign({}, state, {foreignBases});
}
}

更新:@devserkan 提醒我传播运算符“不进行深度复制”,这是 Redux 中的禁忌!所以我去找the updating an item in an array official pattern ,我相信它是这样应用的(同样,未经测试):

let foreignBases = state.foreignBases.map((foreignBase) => {
if (action.baseUser.created === foreignBase.baseuser.created) {
return {action.baseUser};
} else {
return foreignBase
}
});
return Object.assign({}, state, {
...foreignBase,
baseuser: action.baseUser
});

更新 2:评论中的@devserkan 再次贡献了宝贵的见解,这次通过嵌套在部分状态对象中来修复原始的 for 循环。这类似于突变。这种方法避免了这种情况,并允许您仍然使用 for 循环。

for (let i = 0; i < state.foreignBases.length; i++) {
if (action.baseUser.created === state.foreignBases[i].baseuser.created) {
const newItem = {
...state.foreignBases[i],
baseuser: action.baseUser
};
const newforeignBases = Object.assign([], state.foreignBases, {
[i]: newItem
});
return Object.assign({}, state, { foreignBases: newforeignBases });
}
}

关于javascript - 如何在 redux reducer 中改变状态数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52066572/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com