Flux是Facebook用來構建客戶端Web應用的應用架構。它利用單向數據流的方式來組合React中的視圖組件。它更像一個模式而不是一個正式的框架,開發者不須要太多的新代碼就能夠快速的上手Flux。
View層產生了用戶操做(user interfaction)調用了actionCreator的方法,創造了action發送到dispatcher,dispatcher通過判斷後調用store的方法更改狀態, store觸發事件,事件的處理程序就是讓View獲取最新的數據
React(view)=> user click => action creators => actions =>dispatcher => callback => store => change Events + store queries => React(view) 下載:cnpm i flux -S
1> dispatchernpm
事件調度中心,flux模型的中心樞紐,管理着Flux應用中的全部數據流。它本質上是Store的回調註冊。每一個Store註冊它本身並提供一個回調函數。當Dispatcher響應Action時,經過已註冊的回調函數,將Action提供的數據負載發送給應用中的全部Store。應用層級單例!!
2> store架構
負責封裝應用的業務邏輯跟數據的交互。 Store中包含應用全部的數據 Store是應用中惟一的數據發生變動的地方 Store中沒有賦值接口---全部數據變動都是由dispatcher發送到store,新的數據隨着Store觸發的change事件傳回view。Store對外只暴露getter,不容許提供setter!!禁止在任何地方直接操做Store。
3> view框架
controller-view 能夠理解成MVC模型中的controller,它通常由應用的頂層容器充當,負責從store中獲取數據並將數據傳遞到子組件中。簡單的應用通常只有一個controller-view,複雜應用中也能夠有多個。 controller-view是應用中惟一能夠操做state的地方(setState()) view(UI組件) ui-component 職責單一隻容許調用action觸發事件,數據從由上層容器經過屬性傳遞過來。
4> 其餘函數
action creators 做爲dispatcher的輔助函數,一般能夠認爲是Flux中的第四部分。ActionCreators是相對獨立的,它做爲語法上的輔助函數以action的形式使得dispatcher傳遞數據更爲便利。
<!--採用觀察者模式 對事件進行檢測 獲得結果 進行雙向綁定--> const EventEmitter = require('event').EventEmitter //用來綁定事件 var store = Object.assign({},EventEmitter.prototype,{ //合併方法 num: 1, addNumber:(){ this.num++; this.emit('numChange') }, getNum:(){ return this.num }, addNumberChange(callback){ this.on('numChange',callback) } }) export default store
import dispatch from './dispatch.js' const actions = { addNumber(){ let action = { type: 'SAVE_NUMBER' } dispatcher: dispatch(action) } } export default actions
import store from './store' var Dispatcher = require('flux').Dispatcher var dispatcher = new Dispatcher() //派發器 dispatcher.register(funtion(action){ switch(action.type){ case SAVE_NUMBER:store.addNumber();break; } }) export default Dispatcher
import store from './store.js' import actions from './actions.js' constructor(props){ super(props) this.state = { num: store.getNum() } } add(){ actions.addNumber() } compoentDidMount(){ store.addNumberChange(function(){ this.setData({ num: store.getNum() }) }.bind(this)) } <!--view層點擊事件--> <button onClick={this.add.bind(this)}>+</button>