在一个组件中,我有:
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>})
确保保留顺序,否则旧值将覆盖新!!!
完成之后,可以将新状态的值设置为创建的新对象。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句