3

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

目前我正在使用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 进行条件更新的正确方法?

4

1 回答 1

3

您可以使用该$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 
    }
  }
})

该命令还带有简写,因此您可以直接传递该函数,如下所示:

first: current => condition1 ? "iron" : current,
于 2020-10-07T13:56:37.160 回答