将对象存储在React组件的状态中? [英] Storing an object in state of a React component?

查看:207
本文介绍了将对象存储在React组件的状态中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将对象存储在React组件的状态中?如果是,那么我们如何使用 setState 更改该对象中键的值?我认为在语法上不允许写这样的东西:

Is it possible to store an object in the state of a React component? If yes, then how can we change the value of a key in that object using setState? I think it's not syntactically allowed to write something like:

this.setState({ abc.xyz: 'new value' });

在类似的行上,我还有一个问题:是否可以在一个变量中设置一组变量React组件使得它们可以用在组件的任何方法中,而不是将它们存储在一个状态中?

On similar lines, I've another question: Is it okay to have a set of variables in a React component such that they can be used in any method of the component, instead of storing them in a state?

您可以创建一个包含所有这些变量的简单对象,并将其放置在组件级别,就像在组件上声明任何方法一样。

You may create a simple object that holds all these variables and place it at the component level, just like how you would declare any methods on the component.

很可能遇到在代码中包含大量业务逻辑的情况,并且需要使用许多变量,这些变量的值通过多种方法更改,然后您根据这些值更改组件的状态。

Its very likely to come across situations where you include a lot of business logic into your code and that requires using many variables whose values are changed by several methods, and you then change the state of the component based on these values.

因此,您只需保留那些值应直接反映在UI中的变量,而不是将所有这些变量保留在状态中。

So, instead of keeping all those variables in the state, you only keep those variables whose values should be directly reflected in the UI.

如果这种方法比我在这里写的第一个问题更好,那么我不需要在状态中存储一个对象。

If this approach is better than the first question I wrote here, then I don't need to store an object in the state.

推荐答案

除了kiran的帖子,还有更新助手(以前反应插件)。这可以使用安装npm .npm install immutability-helper

In addition to kiran's post, there's the update helper (formerly a react addon). This can be installed with npm using npm install immutability-helper

import update from 'immutability-helper';

var abc = update(this.state.abc, {
   xyz: {$set: 'foo'}
});

this.setState({abc: abc});

这将创建一个具有更新值的新对象,其他属性保持不变。当您需要执行诸如推入数组和同时设置其他值之类的操作时,这会更有用。有些人到处使用它,因为它提供了不变性。

This creates a new object with the updated value, and other properties stay the same. This is more useful when you need to do things like push onto an array, and set some other value at the same time. Some people use it everywhere because it provides immutability.

如果您这样做,您可以使用以下内容来弥补

If you do this, you can have the following to make up for the performance of

shouldComponentUpdate: function(nextProps, nextState){
   return this.state.abc !== nextState.abc; 
   // and compare any props that might cause an update
}

这篇关于将对象存储在React组件的状态中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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