gpt4 book ai didi

javascript - 通过 shouldComponentUpdate 对无状态、函数式组件进行 React 优化

转载 作者:可可西里 更新时间:2023-11-01 02:40:08 25 4
gpt4 key购买 nike

我知道 React 优化的一个关键点是使用 shouldComponentUpdate() 生命周期钩子(Hook)来检查当前状态/ Prop 与下一个/状态 Prop 。

如果我正在构建一个主要使用功能组件而不是基于类的有状态组件(可以访问生命周期 Hook )的 React 应用程序,我是否会放弃这种特定的优化?我可以在功能组件内部执行类似的检查吗?

最佳答案

无状态组件是 future 优化的候选对象,文档对此进行了暗示,但没有详细说明:

In an ideal world, most of your components would be stateless functions because in the future we’ll also be able to make performance optimizations specific to these components by avoiding unnecessary checks and memory allocations. This is the recommended pattern, when possible.

Source


但是目前,如果 props 不变,无状态组件不会通过跳过渲染过程来优化性能。这已得到 React 团队成员的确认:

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).

[...]

There are discussions about having a pureRender flag that you could set on the function, or allowing it to participate in the shouldUpdate lifecycle, but that's currently not implemented. At the moment, stateless functions can not be pure-render.

It is worth keeping in mind that sometimes people abuse/overuse pure-render; it can sometimes be as or more expensive than running the render again, because you're iterating over the array of props and potentially doing things like string compares, which is just extra work for components that ultimately return true and then proceed to rerender anyway. PureRender / shouldComponentUpdate really is considered an escape hatch for performance and is not necessarily something that should be blindly applied to every component.

Source


我从这次讨论中得出的结论是,在某些复杂组件的情况下,与无状态组件相比,通过实现 shouldComponentUpdate 可以提高性能。另一方面,我会认真考虑性能优势是否足以抵消组件增加的复杂性和更大的占用空间。

关于javascript - 通过 shouldComponentUpdate 对无状态、函数式组件进行 React 优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38383832/

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