【问题标题】:lifecycle: componentWillReceiveProps called before componentDidMount生命周期:componentWillReceiveProps 在 componentDidMount 之前调用
【发布时间】:2016-05-24 21:40:48
【问题描述】:

如果我理解正确,组件的 React 生命周期应该确保在 componentWillReceiveProps 之前调用 componentDidMount。当我在组件的初始安装上测试它时,它似乎以这种方式工作。但是当组件之前已经安装并重新安装时,顺序是相反的。这是预期的行为吗?以下代码说明了可以通过这种方式引入的潜在错误:

class Example extends React.Component {
    componentDidMount() { 
        this.something = { foo: 'bar' };
    }
    componentWillReceiveProps(nextProps) {
        this.something.foo;
        // Throws a TypeError if this code is reached before
        // componentDidMount is called.
    }
}

【问题讨论】:

  • 你能在小提琴上分享你的测试台吗? componentWillReceiveProps 在挂载期间不会被调用,因为无论如何道具都会进来。稍后,它在收到新道具时被调用。但是componentDidMount 根本不会被调用,除非该组件已经被首先卸载。

标签: reactjs


【解决方案1】:

简短回答
确实不能保证触发这些方法的顺序。这就是为什么(如您的示例)在 props 和 state 之外使用组件变量不是一个好主意的原因之一。

更好:如果您需要在生命周期事件之外使用它,请将您的 { foo: 'bar' } 置于状态。

更长的答案

componentDidMount() 每个生命周期只调用一次:

  • 在第一次渲染之后(注意:毕竟孩子们也已经渲染了,毕竟孩子们也打电话给他们的componentDidMounts)
  • 如果组件在卸载后渲染(但这确实是一个新的生命周期)

componentWillReceiveProps() 不会在生命周期中的第一次渲染时调用,而是在所有后续渲染时调用 = 当父级再次发送 props 时。

通常,第二次渲染(触发)componentWillReceiveProps 将在组件(及其子组件)完成安装之后出现,因此在 componentDidMount() 之后。

但我可以想到至少 1 个(可能是理论上的)顺序会颠倒的场景:

  1. 组件接收道具,开始渲染。
  2. 当组件正在渲染时,尚未完成渲染,组件会收到新的 props。
  3. componentWillReceiveProps() 已被解雇,(但componentDidMount 尚未被解雇)
  4. 在所有子组件和组件本身完成渲染后,componentDidMount() 将触发。

所以componentDidMount() 不是初始化像您的{ foo: 'bar' } 这样的组件变量的好地方。
componentWillMount() 将是一个更好的生命周期事件。
但是,我不鼓励在 react 组件中使用任何组件范围的变量,并坚持设计原则:

  • 所有组件变量都应该存在于 state 或 props 中(并且是不可变的)
  • 所有其他变量都受生命周期方法的约束(并且不超出此范围)

【讨论】:

    猜你喜欢
    • 2017-01-06
    • 2018-02-17
    • 1970-01-01
    • 2019-01-02
    • 2020-09-19
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多