個人對於React Hooks 的理解
阿新 • • 發佈:2021-06-28
useRef 獲取dom元素
useContext 對React中context本身功能在hooks裡的應用
useReducer 藉助於Redux的語法,做的一個useState的擴充套件,與Redux完全不同,Redux是全域性狀態管理的,而useReduce是管理當前元件的,爭對單元件
useMemo 效能優化快取資料
useCallback效能優化快取函式
useRef
let myref=useRef(null); useEffect(()=>{ console.log(myref.current) },[]) <button ref={myref} />
class類
let {Provider,Consumer}=React.createContext('123') 最外層 <Mycontext.Provider value={"456"}> <Consumer> {value => /*根據上下文 進行渲染相應內容*/} </Consumer> </Mycontext>
hooks
useContext let {Provider,Consumer}=React.createContext('預設值')
效能優化
(對於react父子元件來說,父元件變化,子元件無條件渲染)
CLASS優化方案:scu生命週期和PureComponemt做優化
shoudComponentUpdate(nextProps,nextState){ if(nextState.count!==this.state.count){//可以通過遞迴進行深度比較但是耗費效能,所以最好資料扁平化 return true;//可以渲染 } return false//不可以渲染 }
為此React淺比較可以使用PureComponemt模式純元件,會預設在scu中進行淺比較
class List extends React.PureComponent { constructor(props){ super(props) } shouldComponentUpdate(){} //淺比較 }
在hooks中
useMemo 快取資料
useCallback 快取函式
useMemo
import React,{useState,memo,useMemo} from 'react'; //第一步 用memo包裹子元件 //第二步 父元件使用用useMemo快取變數,有依賴 const Child=memo(({userInfo})=>{return <div>{userInfo.name}<div/>}) function App(){ //const userInfo={name:"kxz"} const userInfo= userMemo(()=>{return {name:"kxz"}},[name]) return <div> <Child userInfo={userInfo}></ Child></div> }