组件之间对React生命周期事件顺序的保证是什么?

Tim*_*rry 1 javascript events lifecycle reactjs

跨单独组件的React生命周期顺序有什么保证,并且在任何地方都清楚地记录了它们?

例如,假设我有:

<div>{ x ? <A /> : <B /> }</div>
Run Code Online (Sandbox Code Playgroud)

在这里,x在true和false之间进行更改将卸载一个组件,然后安装另一个组件。

是否可以保证安装所涉及的生命周期事件在这些元素上触发的顺序?

例如,有据可查的rendercomponentDidMountx更改为true 时,A会先于A 触发。但是,它保证rendercomponentDidMount对遗嘱后一直火componentWillUnmount对于B?

更进一步:如果A和B的孩子在这棵树的下方,并且开关位于顶部,是否会改变?

任何答案都欢迎,但是对此的坚定文件非常感谢。

Deh*_*oos 5

如果您查看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',
    ]);
  });
Run Code Online (Sandbox Code Playgroud)

这种实现背后的原因可以发现 @ 提交信息测试

“这与我们在Fiber中所做的相匹配-并且这样做是在卸载旧视图之前在后台准备新视图的唯一方法。”


还检查React 16.0.0的最近更改日志:React 16.0.0更改日志

When replacing <A /> with <B />, B.componentWillMount now always
happens before A.componentWillUnmount. Previously,
A.componentWillUnmount could fire first in some cases.
Run Code Online (Sandbox Code Playgroud)

因此可以保证此订单!

  • 哇!+1。这个答案应该是正确的! (2认同)