加入收藏 | 设为首页 | 会员中心 | 我要投稿 湖南网 (https://www.hunanwang.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 建站 > 正文

React 性能优化技巧总结

发布时间:2019-03-06 02:05:19 所属栏目:建站 来源:落在起风的地方
导读:本文将从 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. }  

(编辑:湖南网)

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

热点阅读