Javascript 反应添加对象到对象
在一个组件中,我有:Javascript 反应添加对象到对象,javascript,reactjs,Javascript,Reactjs,在一个组件中,我有: 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(
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]=[];
如何添加到此.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?
啊,我明白了。我为您创建了一个简单的。
通常,如果要向处于状态的对象添加新值,则不能同时执行这两项操作,首先需要创建键,然后为其指定值。(这是老办法):
确保保留订单,否则旧值将覆盖新值强>
完成后,可以将新状态的值设置为已创建的新对象 是的,只要把箭头函数变成一个正则函数。Object.assign本质上是“添加”并组合传递的对象的属性,将它们编译成一个。对不起,我迷路了。初学者如何做到这一点?
assign
不仅覆盖旧值,还取决于传递给它的对象的顺序,因为它们是按顺序分配的。如果将空对象作为第一个参数传递,则可以避免修改任何现有对象。如果为True,我将添加它:),因此旧方法是:var ourList=this.state.items;我们的名单=[];this.setState({items:ourList});一般来说是的,但也增加了答案。
var obj = {};
obj["newKey"] = [];
obj.newKey = [<some value>]
Object.assign({<typically new empty object>}, {<the old object you want to change>}, {<the new field + value to add>})