Javascript 将对象存储在 React 组件的状态?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27105257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Storing an object in state of a React component?
提问by Rahul Dole
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:
是否可以将对象存储在 React 组件的状态中?如果是,那么我们如何使用 更改该对象中键的值setState?我认为在语法上不允许写这样的东西:
this.setState({ abc.xyz: 'new value' });
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?
在类似的方面,我还有另一个问题:在 React 组件中有一组变量可以在组件的任何方法中使用,而不是将它们存储在状态中吗?
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.
很可能会遇到这样的情况:您在代码中包含了大量业务逻辑,并且需要使用许多变量,这些变量的值通过多种方法更改,然后您根据这些值更改组件的状态。
So, instead of keeping all those variables in the state, you only keep those variables whose values should be directly reflected in the UI.
因此,不是将所有这些变量都保留在状态中,而是只保留那些值应该直接反映在 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.
如果这种方法比我在这里写的第一个问题更好,那么我不需要在状态中存储一个对象。
采纳答案by Brigand
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
除了 kiran 的帖子,还有更新助手(以前是 react 插件)。这可以使用 npm 安装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
}
回答by kiran
this.setState({ abc.xyz: 'new value' });syntax is not allowed. You have to pass the whole object.this.setState({abc: {xyz: 'new value'}});If you have other variables in abc
var abc = this.state.abc; abc.xyz = 'new value'; this.setState({abc: abc});You can have ordinary variables, if they don't rely on this.props and
this.state.
this.setState({ abc.xyz: 'new value' });不允许使用语法。你必须传递整个对象。this.setState({abc: {xyz: 'new value'}});如果你在 abc 中有其他变量
var abc = this.state.abc; abc.xyz = 'new value'; this.setState({abc: abc});你可以有普通变量,如果它们不依赖 this.props 和
this.state.
回答by PranavPinarayi
You can use ES6 spreadon previous values in the object to avoid overwrite
您可以在对象中的先前值上使用ES6 扩展以避免覆盖
this.setState({
abc: {
...this.state.abc,
xyz: 'new value'
}
});
回答by jasonseminara
this.setState({abc: {xyz: 'new value'}});will NOT work, as state.abcwill be entirely overwritten, not merged.
this.setState({abc: {xyz: 'new value'}});将不起作用,因为state.abc将被完全覆盖,而不是合并。
This works for me:
这对我有用:
this.setState((previousState) => {
previousState.abc.xyz = 'blurg';
return previousState;
});
Unless I'm reading the docs wrong, Facebook recommends the above format. https://facebook.github.io/react/docs/component-api.html
除非我读错了文档,否则 Facebook 建议使用上述格式。 https://facebook.github.io/react/docs/component-api.html
Additionally, I guess the most direct way without mutating state is to directly copy by using the ES6 spread/rest operator:
另外,我想不改变状态的最直接方法是使用 ES6 扩展/休息运算符直接复制:
const newState = { ...this.state.abc }; // deconstruct state.abc into a new object-- effectively making a copy
newState.xyz = 'blurg';
this.setState(newState);
回答by Ogglas
Even though it can be done via immutability-helperor similar I do not wan't to add external dependencies to my code unless I really have to. When I need to do it I use Object.assign. Code:
即使它可以通过immutability-helper或类似方法完成,我也不想在我的代码中添加外部依赖项,除非我真的必须这样做。当我需要这样做时,我使用Object.assign. 代码:
this.setState({ abc : Object.assign({}, this.state.abc , {xyz: 'new value'})})
Can be used on HTML Event Attributes as well, example:
也可以用于 HTML 事件属性,例如:
onChange={e => this.setState({ abc : Object.assign({}, this.state.abc, {xyz : 'new value'})})}
回答by Kevin Danikowski
Easier way to do it in one line of code
在一行代码中更简单的方法
this.setState({ object: { ...this.state.object, objectVarToChange: newData } })

