Javascript 使用不变性助手修改数组的每个值
我正在努力找出最佳做法是使用 例如,如果我在我的州有这个:Javascript 使用不变性助手修改数组的每个值,javascript,arrays,reactjs,immutability,Javascript,Arrays,Reactjs,Immutability,我正在努力找出最佳做法是使用 例如,如果我在我的州有这个: this.state = { items: [ { name: "test", subItems: [ {val: false}, {val: true}, {val: false} ] }, { name: "test2", su
this.state = {
items: [
{
name: "test",
subItems: [
{val: false}, {val: true}, {val: false}
]
},
{
name: "test2",
subItems: [
{val: true}, {val: true}, {val: false}
]
}
]
}
我想将每个val
设置为false
,我该怎么做呢
我可以一次做一个,但一定有更好的方法:
let elements = update(this.state.items, {
[idx1]:{
subItems:{
[idx2]:{
val: {
$set: false
}
}
}
}
});
这当然是可能的,但它的一切,但可读性或可理解的第一眼
const nextState = update(state, {
items: {
$apply: (items) => {
return items.map(item => {
return update(item, {
subItems: {
$apply: (subItems) => {
return subItems.map(subItem => {
return update(subItem, {
val: {
$set: false
}
})
})
}
}
})
})
}
}
});
试试这个
this.state = {
items: [
{
name: "test",
subItems: [
{val: false}, {val: true}, {val: false}
]
},
{
name: "test2",
subItems: [
{val: true}, {val: true}, {val: false}
]
}
]
}
使用函数式编程
this.state.items
.filter((item) => item.name === test).subitems
.map((subItem) => {
subitem.forEach( (key) => {
{ [key]: !subitem[key] }
})
})
对于具有不变性且无帮助者的ES6解决方案:
this.setState({
// This is if you have other state besides items.
...this.state,
items: this.state.items.map(item => ({
...item,
subItems: item.subItems.map(subItem => ({
...subItem,
val: false // or e.g. setter as a function of (item, subItem)
}))
}))
});
在我看来,它比更新助手更容易。如果要将假布尔值和真布尔值的组合设置为与将all设置为false相对应的值,会发生什么情况?有什么优雅的方法可以做到这一点吗?我假设OP想要更新
this.state
,但这不会返回一个完整的状态来替换旧的状态。