如何在React中更新嵌套状态属性

本文翻译自:How to update nested state properties in React

I'm trying to organize my state by using nested property like this: 我试图通过使用这样的嵌套属性来组织我的状态:

this.state = {
   someProperty: {
      flag:true
   }
}

But updating state like this, 但是像这样更新状态

this.setState({ someProperty.flag: false });

doesn't work. 不起作用。 How can this be done correctly? 如何正确完成?


#1楼

参考:https://stackoom.com/question/2UARb/如何在React中更新嵌套状态属性


#2楼

In order to setState for a nested object you can follow the below approach as I think setState doesn't handle nested updates. 为了设置嵌套对象的setState ,可以遵循以下方法,因为我认为setState不处理嵌套更新。

var someProperty = {...this.state.someProperty}
someProperty.flag = true;
this.setState({someProperty})

The idea is to create a dummy object perform operations on it and then replace the component's state with the updated object 想法是创建一个虚拟对象,对其执行操作,然后用更新的对象替换组件的状态

Now, the spread operator creates only one level nested copy of the object. 现在,散布运算符仅创建对象的一层嵌套副本。 If your state is highly nested like: 如果您的状态是高度嵌套的,例如:

this.state = {
   someProperty: {
      someOtherProperty: {
          anotherProperty: {
             flag: true
          }
          ..
      }
      ...
   }
   ...
}

You could setState using spread operator at each level like 您可以在每个级别使用传播运算符来设置状态,例如

this.setState(prevState => ({
    ...prevState,
    someProperty: {
        ...prevState.someProperty,
        someOtherProperty: {
            ...prevState.someProperty.someOtherProperty, 
            anotherProperty: {
               ...prevState.someProperty.someOtherProperty.anotherProperty,
               flag: false
            }
        }
    }
}))

However the above syntax get every ugly as the state becomes more and more nested and hence I recommend you to use immutability-helper package to update the state. 但是,随着状态变得越来越嵌套,上述语法变得非常丑陋,因此,我建议您使用immutability-helper程序包来更新状态。

See this answer on how to update state with immutability helper . 有关如何使用immutability helper更新状态的信息,请参immutability helper答案。


#3楼

There are many libraries to help with this. 有很多库可以帮助您解决此问题。 For example, using immutability-helper : 例如,使用immutability-helper

import update from 'immutability-helper';

const newState = update(this.state, {
  someProperty: {flag: {$set: false}},
};
this.setState(newState);

Using lodash/fp set: 使用lodash / fp设置:

import {set} from 'lodash/fp';

const newState = set(["someProperty", "flag"], false, this.state);

Using lodash/fp merge: 使用lodash / fp合并:

import {merge} from 'lodash/fp';

const newState = merge(this.state, {
  someProperty: {flag: false},
});

#4楼

一行编写

this.setState({ someProperty: { ...this.state.someProperty, flag: false} });

#5楼

If you are using ES2015 you have access to the Object.assign. 如果您使用的是ES2015,则可以访问Object.assign。 You can use it as follows to update a nested object. 您可以如下使用它来更新嵌套对象。

this.setState({
  someProperty: Object.assign({}, this.state.someProperty, {flag: false})
});

You merge the updated properties with the existing and use the returned object to update the state. 您将更新后的属性与现有属性合并,并使用返回的对象来更新状态。

Edit: Added an empty object as target to the assign function to make sure the state isn't mutated directly as carkod pointed out. 编辑:将一个空对象作为目标分配给assign函数,以确保状态不会像carkod所指出的那样直接突变。


#6楼

Here's a variation on the first answer given in this thread which doesn't require any extra packages, libraries or special functions. 这是此线程中给出的第一个答案的变体,不需要任何额外的程序包,库或特殊功能。

state = {
  someProperty: {
    flag: 'string'
  }
}

handleChange = (value) => {
  const newState = {...this.state.someProperty, flag: value}
  this.setState({ someProperty: newState })
}

In order to set the state of a specific nested field, you have set the whole object. 为了设置特定嵌套字段的状态,您已经设置了整个对象。 I did this by creating a variable, newState and spreading the contents of the current state into it first using the ES2015 spread operator . 为此,我创建了一个变量newState首先使用ES2015 Spread 运算符将当前状态的内容扩展到其中。 Then, I replaced the value of this.state.flag with the new value (since I set flag: value after I spread the current state into the object, the flag field in the current state is overridden). 然后,我取代的值this.state.flag用新的值(因为我设定flag: value 我传播的当前状态到所述对象,该flag在当前状态字段被重写)。 Then, I simply set the state of someProperty to my newState object. 然后,我只是将someProperty的状态设置为我的newState对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值