【问题标题】:why is componentWillReceiveProps deprecated?为什么不推荐使用 componentWillReceiveProps?
【发布时间】:2018-08-23 08:03:09
【问题描述】:

我通读了https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#fetching-external-data-when-props-change。我仍然无法理解为什么他们必须弃用 componentWillReceiveProps。
在 componentWillReceiveProps 中进行 ajax 调用有什么害处?一旦 ajax 调用返回值,我就会更新状态,从而重新渲染组件。

【问题讨论】:

标签: reactjs


【解决方案1】:

componentWillReceiveProps 是一个同步钩子。在此钩子中调用异步函数(如数据获取)需要在设置新道具和数据加载完成之间进行渲染。

但getDerivedStateFromProps 是一个异步 钩子,不需要任何额外的渲染。因此,componentWillReceiveProps 被弃用,原因如下:

  1. 使用 getDerivedStateFromProps
  2. 或者,使用 componentDidUpdate

不会给您带来不必要的渲染。请注意,getDerivedStateFromProps 仅在极少数情况下使用。所以,我建议你尽量使用componentDidUpdate钩子。


比较 componentWillMount 和 componentDidMount 时会发生类似的情况。每当您需要操作异步操作并完全忘记 componentWillMount 时,请使用 componentDidMount。关于 componentDidMount 的更多解释在我的另一个 post 中。

【讨论】:

  • 你能解释一下什么是“同步钩子”吗?为什么你更喜欢 componentDidUpdate 而不是 componentWillReceiveProps
  • 我的困惑到此结束。非常感谢!
【解决方案2】:

我的理解是,如果正在调用 componentWillReceiveProps() 方法,则组件的某些属性已更改,应通知该组件并可能再次重新渲染。

在 componentWillReceiveProps() 内部进行 ajax 调用可能会中断该流程。

我的直觉是,我们被温柔地引导在组件之外进行 ajax 调用,并通过属性传递这些 ajax 调用的所有结果。它使您的组件非常干净且可测试。

【讨论】:

    猜你喜欢
    • 2016-02-23
    • 2017-11-04
    • 2011-10-22
    • 2011-04-11
    • 2021-10-12
    • 2012-12-07
    • 2012-05-16
    • 2020-06-29
    • 2014-08-11
    相关资源
    最近更新 更多