Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[React] 如何避免不必要的渲染?【热度: 632】 #590

Open
yanlele opened this issue Oct 4, 2023 · 0 comments
Open

[React] 如何避免不必要的渲染?【热度: 632】 #590

yanlele opened this issue Oct 4, 2023 · 0 comments
Labels
web框架 web 框架相关知识 腾讯 公司标签
Milestone

Comments

@yanlele
Copy link
Member

yanlele commented Oct 4, 2023

关键词:react 渲染优化

在 React 中,有几种方法可以避免不必要的渲染,以提高性能和优化应用程序的渲染过程:

  1. 使用 PureComponent 或 shouldComponentUpdate 方法:继承 PureComponent 类或在自定义组件中实现 shouldComponentUpdate 方法,以检查组件的 props 和 state 是否发生变化。如果没有变化,则阻止组件的重新渲染。这种方式适用于简单的组件,并且可以自动执行浅比较。

  2. 使用 React.memo 高阶组件:使用 React.memo 包装函数组件,以缓存组件的渲染结果,并仅在其 props 发生变化时重新渲染。这种方式适用于函数组件,并且可以自动执行浅比较。

  3. 避免在 render 方法中创建新对象:由于对象的引用发生变化,React 将会认为组件的 props 或 state 发生了变化,从而触发重新渲染。因此,应尽量避免在 render 方法中创建新的对象,尤其是在大型数据结构中。

  4. 使用 key 属性唯一标识列表项:在渲染列表时,为每个列表项指定唯一的 key 属性。这样,当列表项重新排序、添加或删除时,React 可以更准确地确定哪些列表项需要重新渲染,而不是重新渲染整个列表。

  5. 使用 useCallback 和 useMemo 避免不必要的函数和计算:使用 useCallback 缓存函数引用,以确保只有在其依赖项发生变化时才重新创建函数。使用 useMemo 缓存计算结果,以确保只有在其依赖项发生变化时才重新计算结果。这些钩子函数可以帮助避免不必要的函数创建和计算过程,从而提高性能。

  6. 使用 React.lazy 和 Suspense 实现按需加载组件:使用 React.lazy 函数和 Suspense 组件可以实现按需加载组件,只在需要时才加载组件代码。这可以减少初始渲染时的资源负载。

@yanlele yanlele added web框架 web 框架相关知识 腾讯 公司标签 labels Oct 4, 2023
@yanlele yanlele added this to the milestone Oct 4, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
web框架 web 框架相关知识 腾讯 公司标签
Projects
None yet
Development

No branches or pull requests

1 participant