gpt4 book ai didi

performance - 带有 shouldComponentUpdate 的组件与无状态组件。表现?

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

我知道无状态组件使用起来更舒服(在特定场景下),但是既然你不能使用shouldComponentUpdate,这是否意味着组件将在每次props更改时重新渲染?我的问题是,使用带有智能 shouldComponentUpdate 的类组件是否比使用无状态组件更好(从性能角度来看)。

就性能而言,无状态组件是更好的解决方案吗?考虑这个愚蠢的例子:

const Hello =(props) =>(
<div>
<div> {props.hello}</div>
<div>{props.bye}</div>
</div>);

对比

class Hello extends Component{
shouldComponentUpdate(nextProps){
return nextProps.hello !== this.props.hello
};
render() {
const {hello, bye} = this.props;
return (
<div>
<div> {hello}</div>
<div>{bye}</div>
</div>
);
}
}

假设这些组件都有 2 个 props,并且我们只想跟踪其中一个并更新其中一个(这是一种常见的用例),那么使用无状态功能组件或类组件会更好吗?

更新

在做了一些研究之后,我同意标记的答案。尽管类组件(使用 shouldComponentUpdate)的性能更好,但对于简单组件来说,这种改进似乎可以忽略不计。所以我的看法是这样的:

  • 对于复杂的组件,请使用由 PureComponent 或 Component 扩展的类(取决于您是否要实现自己的 shouldComponentUpdate)
  • 对于简单组件,请使用功能组件,即使这意味着重新渲染会运行
  • 尝试减少最接近的类基组件的更新量,以使树尽可能静态(如果需要)

最佳答案

我认为你应该阅读Stateless functional components and shouldComponentUpdate #5677

For complex components, defining shouldComponentUpdate (eg. pure render) will generally exceed the performance benefits of stateless components. The sentences in the docs are hinting at some future optimizations that we have planned, whereby we won't allocate an internal instance for stateless functional components (we will just call the function). We also might not keep holding the props, etc. Tiny optimizations. We don't talk about the details in the docs because the optimizations aren't actually implemented yet (stateless components open the doors to these optimizations).

https://github.com/facebook/react/issues/5677#issuecomment-165125151

There are currently no special optimizations done for functions, although we might add such optimizations in the future. But for now, they perform exactly as classes.

https://github.com/facebook/react/issues/5677#issuecomment-241190513

我还建议检查 https://medium.com/missive-app/45-faster-react-functional-components-now-3509a668e69f

To measure the change, I created this benchmark, the results are quite staggering! From just converting a class-based component to a functional one, we get a little 6% speedup. But by calling it as a simple function instead of mounting, we get a ~45﹪ total speed improvement.

回答这个问题:这要看情况。如果您有复杂/繁重的组件,您可能应该实现shouldComponentUpdate。否则使用常规功能应该没问题。我认为为像 Hello 这样的组件实现 shouldComponentUpdate 不会产生很大的影响,它可能不值得花时间实现。您还应该考虑从 PureComponent 而不是 Component 进行扩展。

关于performance - 带有 shouldComponentUpdate 的组件与无状态组件。表现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45795380/

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