【问题标题】:Modifying each value of array with immutability helper使用不变性助手修改数组的每个值
【发布时间】:2017-06-03 11:32:15
【问题描述】:

我正在努力找出最佳做法是使用immutability helper 修改对象数组中的每个值。

例如,如果我在我的州有这个:

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

【问题讨论】:

    标签: javascript arrays reactjs immutability


    【解决方案1】:

    这当然是可能的,但它的一切都是乍看之下可读或可理解的。

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

    【讨论】:

    • 当您想设置 false 和 true 布尔值的组合而不是将 all 设置为 false 时会发生什么?有什么优雅的方法可以做到这一点?
    【解决方案2】:

    对于具有不变性的 ES6 解决方案,destructuring 并且没有助手:

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

    在我看来比更新助手更容易。

    【讨论】:

      【解决方案3】:

      试试这个

      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,但这不会返回一个完整的状态来替换旧的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-29
      • 2015-09-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多