ReactJS更新状态数组中的单个对象

我有一个称为状态this.state.devicesdevice对象数组

说我有功能

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对象。但是,在每次通话中,实际上仅更新其中一个或两个设备。

我有什么选择?

在我的确切情况下,a device是一个定义如下的对象:

function Device(device) {

this.id = device.id;

// And other properties included

}

因此,数组中的每个项目state.devices都是this的特定瞬间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没有将其传递给它。

回答:

您可以使用react 不变性助手。

从文档:

var initialArray = [1, 2, 3];

var newArray = update(initialArray, {$push: [4]}); // => [1, 2, 3, 4]

initialArray仍为[1、2、3]。

因此,对于您的示例,您将需要执行以下操作:

if (index !== -1) {

var deviceWithMods = {}; // do your stuff here

this.setState(update(this.state.devices, {index: {$set: deviceWithMods }}));

}

根据device模型的复杂程度,您可以就地“修改”对象属性:

if (index !== -1) {

this.setState(update(this.state.devices[index], {name: {$set: 'a new device name' }}));

}

以上是 ReactJS更新状态数组中的单个对象 的全部内容, 来源链接: utcz.com/qa/424462.html

回到顶部