加入收藏 | 设为首页 | 会员中心 | 我要投稿 开发网_开封站长网 (http://www.0378zz.com/)- 科技、AI行业应用、媒体智能、低代码、办公协同!
当前位置: 首页 > 运营中心 > 建站资源 > 优化 > 正文

React 性能优化技巧总结

发布时间:2019-02-27 09:34:21 所属栏目:优化 来源:落在起风的地方
导读:副标题#e# 本文将从 render 函数的角度总结 React App 的优化技巧。需要提醒的是,文中将涉及 React 16.8.2 版本的内容(也即 Hooks),因此请至少了解 useState 以保证食用效果。 正文开始。 当我们讨论 React App 的性能问题时,组件的渲染速度是一个重要

我们来看下下面的例子:

  1. import React, { useState } from "react";  
  2. import ReactDOM from "react-dom";  
  3.   
  4. function App() {  
  5.   const [isFooVisible, setFooVisibility] = useState(false);  
  6.   
  7.   return (  
  8.     <div className="App">  
  9.       {isFooVisible ? (  
  10.         <Foo hideFoo={() => setFooVisibility(false)} />  
  11.       ) : (  
  12.         <button onClick={() => setFooVisibility(true)}>Show Foo </button>  
  13.       )}  
  14.       <Bar name="Bar" />  
  15.     </div>  
  16.   );  
  17. }  
  18.   
  19. function Foo({ hideFoo }) {  
  20.   return (  
  21.     <>  
  22.       <h1>Foo</h1>  
  23.       <button onClick={hideFoo}>Hide Foo</button>  
  24.     </>  
  25.   );  
  26. }  
  27.   
  28. function Bar({ name }) {  
  29.   return <h1>{name}</h1>;  
  30. }  
  31.   
  32. const rootElement = document.getElementById("root");  
  33. ReactDOM.render(<App />, rootElement);  

可以看到,只要父组件 App 的状态值 isFooVisible 发生变化,Foo 和 Bar 就都会被重新渲染。

这里因为为了决定 Foo 是否要被渲染出来,我们需要将 isFooVisible 放在 App中维护,因此也就不能将状态拆出放到更低的层级。不过,在 isFooVisible 发生变化时重新渲染 Bar 仍然是不必要的,因为 Bar 并不依赖 isFooVisible。我们只希望 Bar 在传入属性 name 变化时重新渲染。

那我们该怎么搞呢?两种方法。

其一,对 Bar 做记忆化(memoize):

  1. const Bar = React.memo(function Bar({name}) {  
  2.   return <h1>{name}</h1>;  
  3. });  

这就能保证 Bar 只在 name 发生变化时才重新渲染。

此外,另一个方法就是让 Bar 继承 React.PureComponent 而非 React.Component:

  1. class Bar extends React.PureComponent {  
  2.  render() {  
  3.    return <h1>{name}</h1>;  
  4.  }  
  5. }  

(编辑:开发网_开封站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读