reactjs组件优化:setState的反复render问题
生活随笔
收集整理的這篇文章主要介紹了
reactjs组件优化:setState的反复render问题
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
組件優(yōu)化
Component的2個問題
只要執(zhí)行setState(),即使不改變狀態(tài)數(shù)據(jù), 組件也會重新render() ==> 效率低
只當前組件重新render(), 就會自動重新render子組件,縱使子組件沒有用到父組件的任何數(shù)據(jù) ==> 效率低
效率高的做法
只有當組件的state或props數(shù)據(jù)發(fā)生改變時才重新render()
原因
Component中的shouldComponentUpdate()總是返回true
解決
辦法1: 重寫shouldComponentUpdate()方法比較新舊state或props數(shù)據(jù), 如果有變化才返回true, 如果沒有返回false 辦法2: 使用PureComponentPureComponent重寫了shouldComponentUpdate(), 只有state或props數(shù)據(jù)有變化才返回true注意: 只是進行state和props數(shù)據(jù)的淺比較, 如果只是數(shù)據(jù)對象內(nèi)部數(shù)據(jù)變了, 返回false 不要直接修改state數(shù)據(jù), 而是要產(chǎn)生新數(shù)據(jù) 項目中一般使用PureComponent來優(yōu)化總結(jié)
以上是生活随笔為你收集整理的reactjs组件优化:setState的反复render问题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: reactjs Fragment的作用
- 下一篇: reactjs render props