在我的组件中:
constructor() {
super();
this.state = {
lists: [],
items: {}
};
}
handleAddList(s) {
var temp= this.state.lists.slice(0,this.state.lists.length);
temp.push(s);
this.setState({lists: temp},function(){
var toAdd={};
toAdd[s]=[];
如何将 toAdd 添加到 this.state.items ?
更新,
我想我得到它与以下工作:
var ourLists = this.states.items;
ourlists[s] = [];
and then just setState.
我无法理解两行的基本语法:
toAdd[s] = []; is this just the way you specify a key value pair where the value is an array?
啊,我明白了。
最佳答案
我创建了一个简单的 codepen为你。 一般来说,如果您想为状态中的对象添加新值,您不能同时执行这两项操作,首先您需要创建键,然后再为其赋值。 (这将是旧方法):
var obj = {};
obj["newKey"] = [];
obj.newKey = [<some value>]
现在您可以使用 Object.assign()
这将帮助您向对象添加新属性,同时保持事物的秩序。按顺序我的意思是:
Object.assign(
{<typically new empty object>},
{<the old object you want to change>},
{<the new field + value to add>}
)
确保保持顺序,否则旧值会覆盖新值!!!
完成后,您可以将新状态的值设置为您创建的新对象。
关于javascript - react 将对象添加到对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47601217/