gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:07:54 25 4
gpt4 key购买 nike

我需要更新嵌套对象的一些键,但每个键是否更新都带有一些 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 进行条件更新的正确方法?

最佳答案

您可以使用 $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,

关于javascript - 如何使用 Immutability-helper 进行条件更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64244542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com