问题描述
我有一个名为 this.state.devices
的状态,它是 device
对象的数组.
I have a state called this.state.devices
which is an array of device
objects.
说我有一个功能
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});
}
}
这里的问题是,每次调用 this.updateSomething
时,整个数组都会更新,因此整个DOM都将重新呈现.在我的情况下,这导致浏览器冻结,因为我几乎每秒都要调用此函数,并且有许多 device
对象.但是,在每次通话中,这些设备中只有一个或两个实际上被更新.
Problem here is that every time this.updateSomething
is called, the entire array is updated, and so the entire DOM gets re-rendered. In my situation, this causes the browser to freeze as I am calling this function pretty every second, and there are many device
objects. However, on every call, only one or two of these devices are actually updated.
我有什么选择?
编辑
根据我的实际情况,设备
是一个定义如下的对象:
In my exact situation, a device
is an object that is defined as follows:
function Device(device) {
this.id = device.id;
// And other properties included
}
因此, state.devices
数组中的每个项目都是该 Device
的特定时刻,即我所拥有的某个地方:
So each item in the array of state.devices
is a specific instant of this Device
, i.e. somewhere I'd have:
addDevice: function (device) {
var newDevice = new Device(device);
this.setState({devices: this.state.devices.push(device)});
}
我更新后的答案如何进行 updateSomething
,我有:
My updated answer how on to updateSomething
, I have:
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
var updatedDevices = update(devices[index], {someField: {$set: device.someField}});
this.setState(updatedDevices);
}
}
现在的问题是,我得到一个错误,提示无法读取 id
的未定义值,并且该错误来自函数Device()
;似乎正在调用新的 new Device()
,并且没有将 device
传递给它.
Problem now is that I get an error that says cannot read the undefined value of id
, and it is coming from the function Device()
; it seems that a new new Device()
is being called and the device
is not passed to it.
推荐答案
您可以使用react 不变性助手.
You can use the react immutability helpers.
从文档中
简单推送
var initialArray = [1, 2, 3];
var newArray = update(initialArray, {$push: [4]}); // => [1, 2, 3, 4]
initialArray仍为[1、2、3].
因此,在您的示例中,您将需要执行以下操作:
So for your example you will want to do something like this:
if (index !== -1) {
var deviceWithMods = {}; // do your stuff here
this.setState(update(this.state.devices, {index: {$set: deviceWithMods }}));
}
根据您的 device
模型的复杂程度,您可以就地修改"对象属性:
Depending on how complex your device
model is you could just 'modify' the object properties in situ:
if (index !== -1) {
this.setState(update(this.state.devices[index], {name: {$set: 'a new device name' }}));
}
这篇关于ReactJS更新状态数组中的单个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!