使用不可变辅助工具修改数组中的每个值

3

我很难弄清楚使用不可变助手修改对象数组中每个值的最佳实践。

例如,如果我的状态(state)是这样的:

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
        }
      }
    }
  }
});
3个回答

10

这当然是可能的,但一开始看起来无论如何都不可读或理解。

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
                  }
                })
              })
            }
          }
        })
      })
    }
  }
});

当您想将一组假和真的布尔值设置为相反值而不是全部设置为假时,会发生什么?有没有优雅的方法来实现这个目标? - ahmedhosny

3

对于一个具有不可变性的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)
    }))
  }))
});

比起更新助手,这更容易让我看得舒服。

0

试一下这个

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] }

})
})

我认为OP想要更新this.state,但这并不返回一个完整的状态以替换旧状态。 - bebbi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接