gpt4 book ai didi

reactjs - 生命周期: componentWillReceiveProps called before componentDidMount

转载 作者:行者123 更新时间:2023-12-03 13:28:22 27 4
gpt4 key购买 nike

如果我理解正确,组件的 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.
}
}

最佳答案

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

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

较长的答案:

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

  • 第一次渲染之后(注意:在所有子级也渲染之后,并且在所有子级也调用其 componentDidMount 之后)
  • 如果组件在卸载后渲染(但这确实是一个新的生命周期)

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

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

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

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

因此 componentDidMount() 不是初始化组件变量的好地方,例如 { foo: 'bar' }
componentWillMount() 将是一个更好的生命周期事件。
但是,我不鼓励在 React 组件中使用组件范围的变量,并坚持设计原则:

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

关于reactjs - 生命周期: componentWillReceiveProps called before componentDidMount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37410633/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com