您可以使用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' }}));
}