gpt4 book ai didi

reactjs - 为什么使用 getDerivedStateFromProps 而不是 componentDidUpdate?

转载 作者:行者123 更新时间:2023-12-03 12:59:51 25 4
gpt4 key购买 nike

this React Github issue 中所读我看到越来越多

the cost of render() is relatively small

在 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?有什么好处?

谢谢!

最佳答案

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

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

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

关于reactjs - 为什么使用 getDerivedStateFromProps 而不是 componentDidUpdate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49449527/

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