我想在state数组的末尾添加一个元素,这是正确的方法吗?
this.state.arrayvar.push(newelement);
this.setState({arrayvar:this.state.arrayvar});
Run Code Online (Sandbox Code Playgroud)
我担心原地修改阵列push可能会造成麻烦 - 这样安全吗?
制作阵列副本的替代方案,setState这看起来很浪费.
假设我有一个普通对象列表,this.state.list然后我可以使用它来渲染子列表.那么将对象插入的正确方法是什么this.state.list?
以下是我认为它将起作用的唯一方法,因为你不能this.state像文档中提到的那样直接改变.
this._list.push(newObject):
this.setState({list: this._list});
Run Code Online (Sandbox Code Playgroud)
这对我来说似乎很难看.有没有更好的办法?
我有一个叫做对象this.state.devices数组的状态device.
说我有一个功能
updateSomething: function (device) {
var devices = this.state.devices;
var index = devices.map(function(d){
return d.id;
}).indexOf(device.id);
if (index !== -1) {
// do some stuff with device
devices[index] = device;
this.setState({devices:devices});
}
}
Run Code Online (Sandbox Code Playgroud)
这里的问题是,每次this.updateSomething调用时,整个数组都会更新,因此整个DOM都会被重新渲染.在我的情况下,这导致浏览器冻结,因为我每隔一秒调用此函数,并且有许多device对象.但是,在每次通话时,实际上只更新了这些设备中的一个或两个.
我有什么选择?
编辑
在我的确切情况下,a device是一个定义如下的对象:
function Device(device) {
this.id = device.id;
// And other properties included
}
Run Code Online (Sandbox Code Playgroud)
所以数组中的每个项目state.devices都是这个特定的瞬间Device,即我所拥有的某个地方:
addDevice: function (device) {
var newDevice = new Device(device);
this.setState({devices: this.state.devices.push(device)});
}
Run Code Online (Sandbox Code Playgroud)
我的最新答案如何updateSomething,我有: …