为什么使用 getDerivedStateFromProps 而不是 componentDidUpdate? [英] Why use getDerivedStateFromProps instead of componentDidUpdate?

查看:57
本文介绍了为什么使用 getDerivedStateFromProps 而不是 componentDidUpdate?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如在这个 React Github 问题中所读到的那样><块引用>

render() 的开销相对较小

As read in this React Github issue I see more and more that

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

the cost of render() is relatively small

想象一下这个例子:

Imagine this example:

对比

versus

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

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

谢谢!

推荐答案

所以 Dan Abramov 在 Twitter 上回复了

解决方案

a> 并且您应该使用 getDerivedStateFromProps 而不是 componentDidUpdate + setState 的原因似乎有两个:

So Dan Abramov answered on Twitter and it seems like there are 2 reasons why you should use getDerivedStateFromProps instead of componentDidUpdate + setState:

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

setState in componentDidUpdate causes an extra render (not directly perceptible to user but it slows down your app). And you render method can’t assume the state is ready (because it won’t be the first time).

  • 性能原因:它避免了不必要的重新渲染.
  • 由于 getDerivedStateFromProps 在 init 渲染之前被调用,因此您可以在此函数中初始化您的状态,而无需使用构造函数来执行此操作.目前,您必须有一个构造函数或 componentWillMount 来在初始渲染之前初始化您的状态.
    • Performances reason: it avoids unnecessary re-render.
    • As getDerivedStateFromProps is called before rendering on init, you can initialise your state in this function instead of having a constructor to do so. Currently you had to have a constructor or componentWillMount to init your state before initial rendering.
    • 这篇关于为什么使用 getDerivedStateFromProps 而不是 componentDidUpdate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆