React's reconciliation algorithm assumes that without any information to the contrary, if a custom component appears in the same place on subsequent renders, it's the same component as before, so reuses the previous instance rather than creating a new one.
If you were to implement componentWillReceiveProps(nextProps)
, you would see that getting called instead.
It is very unlikely that a <Header>
element is going to generate a DOM that is going to look like what a <Content>
would generate. Instead of spending time trying to match those two structures, React just re-builds the tree from scratch.
As a corollary, if there is a <Header>
element at the same position in two consecutive renders, you would expect to see a very similar structure and it is worth exploring it.
We decided that the two custom components are the same. Since components are stateful, we cannot just use the new component and call it a day. React takes all the attributes from the new component and calls component[Will/Did]ReceiveProps()
on the previous one.
The previous component is now operational. Its render()
method is called and the diff algorithm restarts with the new result and the previous result.
If you give each component a unique key
prop, React can use the key
change to infer that the component has actually been substituted and will create a new one from scratch, giving it the full component lifecycle.
renderContent() {
if (this.state.activeItem === 'Item 1') {
return (
<Content title="First" key="first" />
);
} else {
return (
<Content title="Second" key="second" />
);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…