如何使用 Immutability-helper 进行条件更新

How to do conditional updates with Immutability-helper

我需要更新嵌套对象的一些键,但是每个键是否更新都带有一些if条件。[​​=14=]

目前我正在使用 lodash cloneDeep() 如下所示......效果很好,但我想提高性能所以我想改用 immutability-helper 库。

    state = {
        info : {
            xyz : {
                name : {
                    first : '',
                    last : '',
                },
                age : '',
            }
        }
    }
    
    let newInfo = _.cloneDeep(this.state.info);
    if (some condition)
        newInfo.xyz.name.first = 'iron'
    if (some condition)
        newInfo.xyz.name.last = 'man'
    if (some condition)
        newInfo.xyz.age = 50
    
    this.setState({ info : newInfo});

但问题是不变性助手需要在一个更新调用中进行所有更改。 所以要么我把所有这些 if 条件放在更新调用中。我什至不知道该怎么做,即使我知道,如果我有很多条件和很多键要更新,那会使代码变得非常不可读。

或者创建多个副本(每次更改 1 个)并稍后以某种方式合并它们???

    import update from 'immutability-helper';

    if (some condition)
        newInfo_1 = update(this.state.info, {xyz: {name: {first: {$set: 'iron' }}}} )
    if (some condition)
        newInfo_2 = update(this.state.info, {xyz: {name: {last: {$set: 'man' }}}} )
    if (some condition)
        newInfo_3 = update(this.state.info, {xyz: {age: {$set: 50 }}} )

    // do i merge the newInfo_1, _2 & _3 somehow ???? 
    // this.setState({ info : ????? })

是否有使用 immutability-helper 进行条件更新的正确方法?

您可以使用 $apply 命令有条件地应用更改。它接受一个函数作为参数,并将当前值传递给该函数。所以,你可以这样做:

const condition1 = true;
const condition2 = true;
const condition3 = false;

const updatedInfo = update(this.state.info, {
  xyz: {
    name: {
      first: {
        $apply: current => condition1 ? 'iron' : current 
      },
      last: {
        $apply: current => condition2 ? 'man' : current 
      }
    },
    age: {
      $apply: current => condition3 ? 50 : current 
    }
  }
})

命令也是comes with a shorthand,所以可以直接传函数,像这样:

first: current => condition1 ? "iron" : current,