我最近一直在使用ReactJS,但是当涉及到“关键”属性时,我真的不知道它是如何工作的。
例如,在父组件中,我呈现如下:
render: function() {
// dataList = [{id: 1}, {id: 2}, {id: 3}]; => initial state
// dataList = [{id: 2}, {id: 3}, {id: 4}]; => second dataList state
var someComponentList = [];
this.state.dataList.forEach(function(data) {
someComponentList.push(
<SomeComponent key={data.id} id={data.id}/>
)
})
return (
<div>
{someComponentList}
</div>
)
}在SomeComponent中:
var SomeComponent = React.createClass({
render : function({
// Render work here
}),
componentWillReceiveProps: function(nextProps) {
console.log(this.props.id == nextProps.id);
}
})因此,在componentWillReceiveProps中,我希望在setState()之后得到3个false控制台结果(如果没有给<SomeComponent>提供key属性的话),但实际上我只有一个false,因为ReactJs似乎知道{id: 2}和{id: 3}是相同的,即使在dataList状态下是按不同的顺序提供的。
我找到了一些关于Reactjs官员的简短文档:
当反应和解关键的孩子,它将确保任何有钥匙的孩子将被重新排序(而不是重击)或销毁(而不是重复使用)。
有人能解释一下它的工作原理吗?
发布于 2015-04-28 03:08:59
https://facebook.github.io/react/docs/reconciliation.html#keys
如果您指定了一个键,那么deletion现在可以使用哈希表查找插入、删除、替换和在O(n)中移动。
它只是一个简单的哈希表(兄弟姐妹)查找,并使React尝试重用具有相同密钥的组件。
粗略的解释,
没有钥匙:
1 3
2 4
updateAttributes x3
带钥匙:
1 3 0
0 2 4
列表2,2有键匹配,2没有更改,3有键.3没有更改,4没有键,原始列表中没有节点,所以插入,1将被销毁
https://stackoverflow.com/questions/29909473
复制相似问题