如何更新React中的嵌套状态属性 [英] How to update nested state properties in React

查看:145
本文介绍了如何更新React中的嵌套状态属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用这样的嵌套属性来组织我的状态:

I'm trying to organize my state by using nested property like this:

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

但是像这样更新状态,

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

不起作用。如何才能正确完成?

doesn't work. How can this be done correctly?

推荐答案

为了 setState for一个嵌套的对象你可以按照下面的方法,因为我认为setState不处理嵌套更新。

In order to setState for a nested object you can follow the below approach as I think setState doesn't handle nested updates.

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
          }
          ..
      }
      ...
   }
   ...
}

你可以在每个级别使用spread运算符setState,如

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
            }
        }
    }
}))

然而,随着状态变得越来越嵌套,上面的语法变得丑陋,因此我建议你使用 immutability-helper 包来更新状态。

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.

这篇关于如何更新React中的嵌套状态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆