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

3

我需要更新嵌套对象的某些键,但每个键是否更新都伴随着一些条件语句。

目前我正在使用类似下面的 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条件放在更新调用内部。我甚至不知道如何做到这一点,即使我这样做,如果我有许多条件和许多要更新的键,则会使代码非常难以阅读。
或者创建多个副本(每个更改一个)并稍后合并它们???
    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 进行条件更新?
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,

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