[英]I want to push / add object to the state react native (invalid attempt to spread non iterable instance)
i want to add object to my state and i have search to solve it but all of it doesn't work 我想将对象添加到我的状态,我已经进行搜索来解决它,但所有方法都无法正常工作
this.state = {
value : {name:'test'}
};
i want to add an object {coordinate:'0,0'} in this.state.value 我想在this.state.value中添加一个对象{coordinate:'0,0'}
I tried this one but i got error : invalid attempt to spread non iterable instance 我尝试了此操作,但出现错误:传播非迭代实例的尝试无效
let floors = [...this.state.value];
floors.push({ coordinate: '0,0'});
this.setState({ value:floors });
I tried this one but i got error : invalid attempt to spread non iterable instance 我尝试了此操作,但出现错误:传播非迭代实例的尝试无效
this.setState({
value:[...this.state.value, {coordinate: '0,0'}]
});
I tried this one but i got error : _this2.state.value.concat is not a function 我尝试了这个但我遇到了错误:_this2.state.value.concat不是一个函数
this.setState( {
value: this.state.value.concat({koordinat:coor})
});
please help me to solve it 请帮我解决
You tried to spread a map into an array. 您试图将地图散布到数组中。
If you want to start with an array, then change your initial state: 如果要从数组开始,请更改初始状态:
this.state = { value: [{ name: 'test' }] }
Then you can use your original code, either of the first two examples. 然后,您可以使用原始代码,即前两个示例之一。
Your second example fails for the same reason. 您的第二个示例由于相同的原因而失败。
The third example doesn't make sense, you're trying to concat
onto an object. 第三个示例没有意义,您试图将其concat
到一个对象上。
Based on the comments none of the original code really addressed what you are trying to do, namely, simply adding a property to an existing object. 基于这些注释,原始代码都没有真正解决您要执行的操作,即仅向现有对象添加属性。 As schogges points out, this is trivial: 正如schogges指出的,这很简单:
this.setState({
value: { ...this.state.value, coordinate: '0, 0') }
})
This spreads an existing object into a new object with an additional property. 这会将现有对象扩展为具有其他属性的新对象。
That said: coordinates aren't strings, they're objects. 就是说:坐标不是字符串,而是对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.