【发布时间】:2017-12-02 23:53:31
【问题描述】:
这是基本的想法......
constructor(props) {
super(props);
this.state = {
children: [{id:1},{id:2}], // HERE ARE THE TWO OBJECTS
style: {top: 0}
};
}
现在假设我更新了这两个对象之一,但这些对象被映射到一个组件数组。
<div className="thread">
{this.state.children.map((child) =>
<Post
key={child.id}
id={child.id}
/>
)}
</div>
现在...当我更新其中一个对象时...
changeID (id, newID) { // this is a different function, just an example
let temp = this.state.children;
for (let i = 0; i < temp.length; i++) {
if (temp[i].id === id) {
temp[i].id = newID; // <- update this
}
}
this.setState({
children: temp // <- plug temp[] back as the updated state
});
}
我将新状态重新放入,但它会更新每个映射的对象。
// on one change to one element
id 1 POST UPDATED
id 2 POST UPDATED
1) 它是重新渲染 EVERY 组件(在映射数组中)还是足够聪明地判断作为道具传递给映射组件的状态值是相同的?
2) 如果阵列明显更长,处理能力是否会非常昂贵?
3) 如果是,我怎样才能更好地解决这个问题?建设性的批评是值得赞赏的。
谢谢!
【问题讨论】:
-
你怎么知道它正在更新每个对象?
-
@MayankShukla componentDidUpdate(){console.log("UPDATED");}