gpt4 book ai didi

reactjs - react : componentWillUpdate

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

有人可以解释一下在下一个上下文中到底发生了什么吗:

假设我有一个应用程序组件(父组件),还有一些子组件,例如索引、搜索、关于,这三个组件有它们的子组件。

当我在应用程序组件中调用 componentWillUpdate 时会发生什么,新的状态/ Prop 将会出现,但是叶子(子元素)内部会发生什么,它们会重新渲染自己吗?

假设我在 App 中的这个 componentWillUpdate 中覆盖了 DOM 中的某些内容,并且我将在 componentDidMount 或 componentWillMount 中的叶组件中的 DOM 中覆盖相同的内容...哪个值将是最后一个?

最佳答案

首先,您不应该手动调用componentWillUpdate。如果作为其生命周期的一部分,它会被 React 调用。

根据comment in ReactCompositeComponent.js这是更新阶段发生的情况:

Update Phases:
- componentWillReceiveProps (only called if parent updated)
- shouldComponentUpdate
- componentWillUpdate
- render
- [children's constructors or receive props phases]
- componentDidUpdate

如您所见,App.render 在渲染子组件之前被调用。

如果您出于某种原因想要手动操作 DOM,componentWillUpdate 不是执行此操作的正确位置。每次更新后使用 componentDidUpdate 或在初始渲染后使用 componentDidMount。子级的 componentDidUpdatecomponentDidMount 在父级的生命周期方法之前触发。

关于reactjs - react : componentWillUpdate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34811003/

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