Canberk Morelli 是 OpsGenie 的一名前端工程師,正在使用 React 構建公司內部項目。經過這篇文章可使初學者不要犯一樣的錯誤。html
setState
都會引發組件的從新渲染 re-render每次state 改變或者傳入新的 props 都會調用 shouldComponentUpdate
。前端
shouldComponentUpdate
默認返回 true
,開發者能夠根據本身的邏輯決定是否返回 false
。react
注意:git
shouldComponentUpdate
邏輯可能引起錯誤:應該渲染的時候沒有渲染,或者不該該渲染的時候卻渲染了shouldComponentUpdate
進行復雜的判斷容易引起性能問題,能夠經過 React’s Performance Tools 來查找。setState
對狀態的改變是異步的調用 setState
後,組件的 state
並不會當即改變。github
一個常常犯的錯誤就是在 setState
後立刻使用 this.state
。前端工程師
setState
還有另外一種用法:setState(updater, [callback])
,經過傳遞一個函數 updater
。
第 2 個參數是修改完狀態後的回調,可是不推薦在這裏寫業務邏輯,一個比較不錯的地方是寫到 componentDidUpdate
函數裏。異步
生命週期大概分爲 3 類:函數
掛載:組件被建立並插入到 DOM性能
更新:組件正在從新渲染,通常是由 props 或 state 的改變引發的this
卸載:組件從 DOM 上移除
componentWillReceiveProps
的使用當組件的 props 改變時須要更新 state時使用這個方法。
注意:
componentWillReceiveProps
,所以須要在函數內部比較 this.props
和 nextProps
componentWillReceiveProps
被調用,所以在掛載階段是不會調用 componentWillReceiveProps
的React Developer Tools 能夠更方便的調試 React 應用。
官方推出的 Create React App 讓開發者已零配置的方式快速建立 React 應用。
閱讀原文:I wish I knew these before diving into React
討論地址:我但願在深刻 React 以前知道這些
若是你想參與討論,請點擊這裏