Typography

活版印字


  • Home
  • Archive
  • Categories
  • Tags
  •  

© 2020 alincode

Theme Typography by Makito

Proudly published with Hexo

Flux 生命週期範例

Posted at 2016-03-31 Flux 

完整範例

初始化

第一次 Component 被載入時,會做哪些事?

  • 執行 getInitialState
  • getInitialState 去 Store 拿 state 第一次初始化需要載入的資料
  • 執行 componentWillMount
  • 執行 Component render
  • 執行 componentDidMount
  • componentDidMount 會加入 store 的 addChangeListener
1
TestStore.addChangeListener(this.storeCallback);

有值更動時

執行被 bind 的 onChange

1
<textarea rows="4" cols="50" onChange={this._onChange} value={this.state.text}/>

onChange 取得值後傳給 action

1
2
3
_onChange: function(event) {
TestAction.updateText(event.target.value);
}

Action 呼叫 AppDispatcher,並告訴它要做什麼事(ActionTypes),跟把要更新的值傳給它。

1
2
3
4
5
6
7
8
9
10
module.exports = {
updateText: function(text) {
console.log('=== action updateText ===');
AppDispatcher.dispatch({
type: ActionTypes.UPDATE_TEXT,
text: text
});
},
};

接著 Store 的 dispatcherIndex 被觸發

1
2
3
4
5
6
7
8
9
10
11
12
dispatcherIndex: AppDispatcher.register(function(payload) {
var action = payload.type;
switch(action) {
case TestConstants.ActionTypes.UPDATE_TEXT:
_text = payload.text;
TestStore.emitChange();
break;
default:
console.log('=== store dispatcherIndex default ===');
}
return true; // No errors. Needed by promise in Dispatcher.
})

emitChange 被呼叫後,會通知所有 listen 這個 Store 的 Component,Component 的 callback 會收到通知。

1
2
3
storeCallback: function() {
this.setState(getStateStores());
},

callback 要做的事,就是重新去 Store 拿新的值,並把自己更新(this.setState)。

當 callback 做 setState 的時候,會觸發 shouldComponentUpdate,如果回傳值是 true

會接著執行 componentWillUpdate

然後會重新 render component

render 完後會,會執行 componentDidUpdate

資料來源

  • Component Lifecycle

Share 

 Previous post: Geb 0.13.x 更新重點 Next post: React 防止連點 

© 2020 alincode

Theme Typography by Makito

Proudly published with Hexo