我有以下 React
组件(这只是一个示例):
class MainForm extends React.Component {
constructor(props) {
super(props);
this.state = {
elements : [
{
id: 1, // this is never changed
title: 'Element 1',
data: {
text: 'Initial text for Element 1',
// other properties
...
}
},
.....
]
};
}
}
这里的state
是一个对象数组(就像我代码中的一样)。数组中的所有元素都有id
,并且这个属性永远不会改变!
我想更新这个数组 - 删除元素,添加新元素和最有趣的 - 更新该数组中的一些现有元素。
添加/删除很容易实现,但我在更新现有项目时遇到了困难。
我是 React 新手,所以这是我的方法,它可能有点贵:
updateElements = value => {
// value is the object with some property updated
/* example (data.text is updated)
{
id: 1,
title: 'Element 1',
data: {
text: 'Updated text for Element 1',
// other properties
...
}
}
*/
// there is 'id' for each item so I do map to replace out-dated element with a new one
const updatedElements = this.state.elements.
.map(e => {
if (e.id === value.id) {
return value;
} else {
return e;
}
});
this.setState({
elements: updatedElements
});
}
在我的例子中,这个数组以及存储在其中的对象可能非常大。
必须有一种更有效的方法来使用 React 或纯 JavaScript 来实现这一点,以使其性能更好。
有什么建议吗?
最佳答案
不,你明白了。
编辑处于状态的数组中的项目的最佳方法通常是对其进行映射,返回大多数索引的现有项目,并返回具有所需索引的替换项目。
您说这“非常昂贵”,但是一个只进行很少处理并返回一个主要由对已存在对象的引用组成的新数组的映射在任何方面通常都不昂贵。
如果你不想做这种杂耍,不可变的数据库,如 Immutable.js其他人可以提供帮助。
关于javascript - 有没有更好的方法来更新数组中代表 React 组件状态的某些对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59184113/