gpt4 book ai didi

reactjs - React.Component 与 React.PureComponent

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

官方React docs声明“React.PureComponentshouldComponentUpdate() 仅浅层比较对象”,如果状态为“深层”,则建议不要这样做。

鉴于此,是否有任何理由应该选择 React.PureComponent创建 React 组件时?

问题:

  • 使用 React.Component 对性能有影响吗我们可以考虑选择 React.PureComponent
  • 我猜shouldComponentUpdate()PureComponent仅执行浅层比较。如果是这样的话,是不是可以用这个方法进行更深入的比较呢?
  • “此外, React.PureComponentshouldComponentUpdate() 会跳过整个组件子树的 prop 更新” - 这是否意味着 prop 更改会被忽略?

阅读本文 medium blog 时出现问题,如果有帮助的话。

最佳答案

React.PureComponentReact.Component 之间的主要区别是 PureComponent 对状态进行浅层比较改变。这意味着在比较标量值时,它会比较它们的值,但在比较对象时,它仅比较引用。它有助于提高应用程序的性能。

当您可以满足以下任何条件时,您应该选择 React.PureComponent

  • State/Props 应该是一个不可变的对象
  • 状态/ Prop 不应具有层次结构
  • 当数据发生变化时,您应该调用forceUpdate

如果您使用React.PureComponent,您应该确保所有子组件也是纯组件。

is there any performance impact in using React.component that we may consider going for React.PureComponent?

是的,它将提高您的应用性能(因为浅比较)

I am guessing shouldComponentUpdate() of Purecomponent performs only shallow comparisons . If this is the case can' t the said method used for deeper comparisons?

你猜对了。如果你满足我上面提到的任何一个条件,你就可以使用它。

"Furthermore, React.PureComponent's shouldComponentUpdate() skips prop updates for the whole component subtree" - Does this mean that prop changes are ignored?

是的,如果在浅比较中找不到差异, Prop 更改将被忽略。

关于reactjs - React.Component 与 React.PureComponent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41340697/

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