跨不同组件的 React 生命周期顺序保证是什么?它们是否在任何地方都有清楚的记录?
例如,假设我有:
<div>{ x ? <A /> : <B /> }</div>
此处,x
在 true 和 false 之间切换将卸载一个组件并安装另一个组件。
对于安装中涉及的生命周期事件将在这些元素中触发的顺序,是否有保证?
例如,它是well documented当 x
变为 true 时,A 的 render
将在 A 的 componentDidMount
之前触发。但是,是否保证 A 的 render
和 componentDidMount
总是在 B 的 componentWillUnmount
之后触发?
更进一步:如果 A 和 B 是这棵树中更靠下的 child ,开关在顶部,它会改变吗?
欢迎任何答案,但非常感谢关于此的坚定文档。
最佳答案
如果你查看 React 官方仓库中的测试,你可以轻松找到与此订单相关的相关测试。
it('prepares new child before unmounting old', () => {
const log = [];
class Spy extends React.Component {
UNSAFE_componentWillMount() {
log.push(this.props.name + ' componentWillMount');
}
render() {
log.push(this.props.name + ' render');
return <div />;
}
componentDidMount() {
log.push(this.props.name + ' componentDidMount');
}
componentWillUnmount() {
log.push(this.props.name + ' componentWillUnmount');
}
}
class Wrapper extends React.Component {
render() {
return <Spy key={this.props.name} name={this.props.name} />;
}
}
const container = document.createElement('div');
ReactDOM.render(<Wrapper name="A" />, container);
ReactDOM.render(<Wrapper name="B" />, container);
expect(log).toEqual([
'A componentWillMount',
'A render',
'A componentDidMount',
'B componentWillMount',
'B render',
'A componentWillUnmount',
'B componentDidMount',
]);
});
The reasoning behind this implementation can be found @ commit message for test
"This matches what we do in Fiber -- and doing it this way is the only way we can prepare new views in the background before unmounting old ones."
另请查看 React 16.0.0 最近的更新日志:React 16.0.0 changelog
When replacing <A /> with <B />, B.componentWillMount now always
happens before A.componentWillUnmount. Previously,
A.componentWillUnmount could fire first in some cases.
所以这个顺序是有保证的!
关于javascript - 组件之间的 React 生命周期事件顺序有哪些保证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58135416/