【发布时间】:2015-11-21 04:54:31
【问题描述】:
我有一个名为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});
}
}
这里的问题是每次调用this.updateSomething 时,整个数组都会更新,因此整个DOM 会重新渲染。在我的情况下,这会导致浏览器冻结,因为我每秒都在调用这个函数,并且有很多 device 对象。但是,每次通话时,实际上只有一两个设备得到更新。
我有什么选择?
编辑
在我的确切情况下,device 是一个定义如下的对象:
function Device(device) {
this.id = device.id;
// And other properties included
}
所以state.devices 数组中的每个项目都是这个Device 的特定时刻,即我应该有的地方:
addDevice: function (device) {
var newDevice = new Device(device);
this.setState({devices: this.state.devices.push(device)});
}
我更新的答案如何updateSomething,我有:
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 的未定义值,它来自function Device();似乎正在调用一个新的 new Device() 并且 device 没有传递给它。
【问题讨论】:
-
有一些方法可以阻止每次渲染,例如shouldComponentUpdate,看看这个帖子codementor.io/reactjs/tutorial/understanding-react-js-rendering。此外,如果您找到一种方法将索引与设备一起保存,而不是每次都映射和搜索它,您将节省一些执行时间。您还在技术上更改状态中的数组,应将其视为不可变的,建议按照stackoverflow.com/questions/26505064/… 使用 .slice()
标签: javascript reactjs