【问题标题】:Why use getDerivedStateFromProps instead of componentDidUpdate?为什么使用 getDerivedStateFromProps 而不是 componentDidUpdate?
【发布时间】:2018-03-23 12:20:23
【问题描述】:

正如this React Github issue 中所读,我看到的越来越多

render()的成本比较小

在 React 16.3 中,我想知道为什么要使用新的 getDerivedStateFromProps 而不是 componentDidUpdate?

想象一下这个例子:

getDerivedStateFromProps(nextProps, prevState) {
  if (!prevState.isModalOpen && nextProps.isReady) {
       return { isModalOpen: true };
  }
}

componentDidUpdate(prevProps, prevState) {
  if (!prevState.isModalOpen && this.props.isReady) {
        this.setState({ isModalOpen: true });
  }
}

后者似乎更简单,因为它只使用现有的 API,并且看起来就像我们过去在 componentWillReceiveProps 中所做的那样,所以我不明白为什么用户会选择 getDerivedStateFromProps?有什么好处?

谢谢!

【问题讨论】:

  • 让我也想知道这一点。在组件的 init 和组件的更新中执行相同的逻辑似乎是一种方便的方法。在 React 15 中,我编写了许多在构造函数和 CWP 中调用相同函数的组件。因为这对你来说是一个单一的功能。 twitter.com/dan_abramov/status/960305777968930816
  • 好吧,我认为你是对的,因为这是在 init 上调用的,而 cDU 仅在渲染后调用。但我相信这两个函数之间的唯一区别是,如果你在 cDU 中进行操作,就会多渲染 1 个。

标签: reactjs


【解决方案1】:

所以Dan Abramov answered on Twitter,您应该使用getDerivedStateFromProps 而不是componentDidUpdate + setState 似乎有两个原因:

componentDidUpdate 中的 setState 会导致额外的渲染(用户无法直接感知,但会减慢您的应用程序的速度)。而且你的渲染方法不能假设状态已经准备好了(因为这不是第一次)。

  • 性能原因:它避免了不必要的重新渲染。
  • 由于getDerivedStateFromProps 在初始化渲染之前被调用,您可以在此函数中初始化您的状态,而不是使用构造函数来执行此操作。 目前,您必须有一个构造函数或 componentWillMount 在初始渲染之前初始化您的状态。

【讨论】:

  • 但只有在将 props 设置为 state no 时才使用 getDerivedPropsFromState?
  • @zero_cool 是的。正如 Dan Abramov 在下面的评论中所说,任何不返回新状态的东西都应该进入 componentDidMount。
【解决方案2】:

getDerivedStateFromProps 实际上是 componentWillReceiveProps 的替代品,componentDidMount 不会被弃用。

我很确定是社区决定使用该名称创建静态方法。

这个变化的原因是componentWillReceiveProps was one of the methods that led to confusion and further to some memory leaks in user applications:

其中许多问题会因组件的子集而加剧 生命周期(componentWillMount、componentWillReceiveProps 和 组件将更新)。这些也恰好是生命周期 在 React 社区中引起最大的混乱。对于这些 原因,我们将弃用这些方法以支持更好的 替代品。

这里的Dan Abramov tweet 也更清楚地说明了这一点:

但是,这意味着我们将分道扬镳 17.我们认为getDerivedStateFromProps()中的componentWillReceiveProps() 做同样的工作更好,更不容易混淆。也发生了 cWRP() 确实打乱了我们的数据获取功能计划 可能正在筹备中。 ?

【讨论】:

  • 感谢您的解释,但我认为这并不能真正回答我的问题,即为什么我应该使用它而不是仅仅将逻辑放入 componentDidMount 并忘记那个新功能?
  • @Grsmto 您的假设是错误的 :) 它在哪里说您应该使用 getDerivedStateFromProps 而不是 componentDidUpdate ?因为这是两种不同的钩子方法。
  • 但是如果我可以在componentDidMount 中做同样的事情,为什么他们会引入这个功能呢?这就是我要问的。
  • 它与componentDidUpdate 无关,两者都在组件生命周期的不同步骤中调用,并且会有不同的用例。他们引入了getDerivedStateFromProps 以避免混淆,只留下一种方法而不是三种方法。
  • 您不应该在getDerivedStateFromProps 中获取任何内容。这就是 componentDidUpdatecomponentDidMount 的用途。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-03
  • 1970-01-01
  • 2013-12-07
  • 1970-01-01
相关资源
最近更新 更多