React Component銇儵銈ゃ儠銈点偆銈儷銇娇銇勬柟銇ㄨ瑕氬寲銇椼仧銈点兂銉椼儷

銉┿偆銉曘偟銈ゃ偗銉倰瑕栬鍖

React銈掍娇鐢ㄣ仚銈嬩笂銇ф瑺銇嬨仜銇亜銉┿偆銉曘偟銈ゃ偗銉

銇撱伄銉┿偆銉曘偟銈ゃ偗銉倰瑕栬鍖栥仐銇熴偟銉炽儣銉倰浣滄垚銇椼仸銈忋亱銈娿倓銇欍亸銇椼仸銇裤仧銆

React銉┿偆銉曘偟銈ゃ偗銉倰瑕栬鍖栥仐銇熴偟銉炽儣銉

鏈鍒濄伀瀹熻銇曘倢銈嬨儵銈ゃ儠銈点偆銈儷

銈点兂銉椼儷銈掕銈嬨仺涓鐩灜鐒躲仩銇屻佹渶鍒濄伀瀹熻銇曘倢銈嬨儵銈ゃ儠銈点偆銈儷銇互涓嬨伄5銇ゃ仹銇傘倠銆

  • componentDidMount
  • render
  • componentWillMount
  • getInitialState
  • getDefaultProps

props銇痝etDefaultProps銇с伅銇亸ReactDOM.render銇ф寚瀹氥仐銇熴伝銇嗐亴鑹亜銇熴倎銆乬etDefaultProps銇仾銈嬨伖銇忎娇鐢ㄣ仐銇亜銇汇亞銇岃壇銇勩

getDefaultProps: function() {
  return {name: 'foo'};
},

getInitialState銇痭pm浣跨敤鏅傘伅getInitialState銇с伅銇亸constructor()銇屼娇鐢ㄣ仌銈屻倠銆

涓汇伀鍒濇湡鍊ゃ仾銇┿伄鎸囧畾銇娇鐢ㄣ仌銈屻倠銆備竴鐣渶鍒濄伀瀹熻銇曘倢銈嬨仺瑾槑銇椼仸銇勩倠銈点偆銉堛亴銇傘倠銇実etDefaultProps銇屻亗銈嬨仺銆併仢銇°倝銇屽厛銇伄銇ч枔閬曘亜銆

render(鎻忕敾)銇墠寰屻伀銇痗omponentWillMount銇娿倛銇砪omponentDidMount銇屽疅琛屻仌銈屻倠銇熴倎銆乺ender銇墠寰屻伀鍑︾悊銈掕拷鍔犮仐銇熴亜鍫村悎銇亾銈屻倝銇拷鍔犮仚銈嬨

澶夋洿寰屻伄銉┿偆銉曘偟銈ゃ偗銉

銈点兂銉椼儷銇玜銇ㄥ叆鍔涖仚銈嬨仺浠ヤ笅銇唴瀹广亴琛ㄧず銇曘倢銈嬨

  • componentDidUpdate{"name":"foo"}{"len":0}
  • render
  • componentWillUpdate{"name":"foo"}{"len":1,"val":"a"}
  • shouldComponentUpdate{"name":"foo"}{"len":1,"val":"a"}

涓嬨亱銈夐爢銇鏄庛仚銈嬨仺shouldComponentUpdate銇弿鐢汇仚銈嬨亱銇┿亞銇嬨伄鍒ゅ畾銈掕銇嗐

true銇с亗銈屻伆鎻忕敾銇椼乫alse銇с亗銈屻伆鎻忕敾銇椼仾銇勩

渚嬨亪銇板叆鍔涘ゃ亴鐣般仾銈屻伆true銈掕繑銇椼佸悓銇樸仹銇傘倢銇癴alse銈掕繑銇欍倛銇嗐伀銇欍倢銇扮劇椐勩仾鎻忕敾銈掕銈忋仾銇勩仧銈佸嚘鐞嗐倰杌芥笡銇с亶銈嬨

銈点兂銉椼儷銇с伅ab銈掑叆鍔涘緦銇玜b銈掋偝銉斻兗銇椼仸銉氥兗銈广儓銇椼仸銈傚墠鍥炪仺鍚屻仒鍊ゃ仾銇仹shouldComponentUpdate浠ラ檷銇嚘鐞(鍐嶆弿鐢)銇岀櫤鐢熴仐銇亜銆

shouldComponentUpdate: function(nextProps, nextState) {
  // 銉椼儹銉戙儐銈c伨銇熴伅銈广儐銉笺儓銈掑彈銇戝彇銈嬬洿鍓
  r('shouldComponentUpdate' + j(nextProps) + j(nextState));
  if (this.state.val === nextState.val) {
    return false;
  } else {
    return true;
  }
},

componentWillUpdate銇痳ender鍓嶃伀琛屻亞鍑︾悊銆乧omponentDidUpdate銇痳ender寰屻伀琛屻亞鍑︾悊銇с亗銈嬨

componentWillUnmount

銈点兂銉椼儷銇畊nmount銉溿偪銉炽倰鎶笺仚銇ㄣ併仢銇悕銇氥倞銈炽兂銉濄兗銉嶃兂銉堛亴銈€兂銉炪偊銉炽儓(瑙i櫎)銇曘倢銈嬨

componentWillUnmount銇偝銉炽儩銉笺儘銉炽儓銇屻偄銉炽優銈︺兂銉(瑙i櫎)銇曘倢銇熴仺銇嶃伀琛屻亞鍑︾悊銆傘偄銉炽優銈︺兂銉堛仌銈屻倠銇╥d="app"鍐呫伄鍏ュ姏娆勩伅銇亸銇倠銆

componentWillReceiveProps

componentWillReceiveProps銇偝銉炽儩銉笺儘銉炽儓銇畃rops銇屽鏇淬仌銈屻仧銇ㄣ亶銇銇嗗嚘鐞嗐仹銇傘倠銆

銈点兂銉椼儷銇畆enderNameBar銉溿偪銉炽倰鎶笺仚銇ㄥ垵鏈熴伄name='foo'銇畃rops銇宯ame='bar'銇т笂鏇搞亶銇曘倢銈嬨亾銇ㄣ伀銈堛倞銆乸rops銇屽鏇淬仌銈屻倠銇熴倎componentWillReceiveProps銇屽疅琛屻仌銈屻倠銆

componentDidCatch

componentDidCatch銇偍銉┿兗銇岀櫤鐢熴仐銇熴仺銇嶃伀琛屻亞鍑︾悊銆

鍒ラ擡rrorMsg銇倛銇嗐仾class銈掍綔銇c仸銆併偍銉┿兗鐧虹敓鏅傘伅ErrorMsg銇甤lass銇唴瀹广倰琛ㄧず銇曘仜銈嬩娇銇勬柟銈掋仚銈嬨

<ErrorMsg>
 <Counter name='foo' />
<ErrorMsg>

https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html

React銉┿偆銉曘偟銈ゃ偗銉倰瑕栬鍖栥仐銇熴偟銉炽儣銉