目录结构
| src
-| index.js
-| app.js
-| dispatcher.js
-| store.js
安装flux
- 在dispatcher.js引入flux中的{Dispatcher}
- 实例化Dispatcher,并注册
const dispatcher = new Dispatcher()
dispatcher.refister(callback)
引入EventEmitter
- 在store.js中引入events中的EventEmitter
events为nodejs中的模块
- 将需要储存的数据与EventEmitter.prototype整合
const store = Object.assign(otherObj, EventEmitter.prototype)
数据流
- dom事件触发dispatcher发送action
- 匹配action之后,调用store中的方法
- 调用store完成之后,触发监听事件,更新页面
store.on('event',callback)
graph LR
A[Action]-->B[Dispatcher]
B[Dispatcher]-->C[Store]
C[Store]-->D[View]
D[view]-->| Action |B[Dispatcher]
- View:视图层
- Action(动作):视图层发出的消息(比如mouseClick)
- Dispatcher(派发器):用来接收Actions、执行回调函数
- Store(数据层):用来存放应用的状态,一旦发生变动,就提醒Views要更新页面
- 用户访问 View
- View 发出用户的 Action
- Dispatcher 收到 Action,要求 Store 进行相应的更新
- Store 更新后,发出一个"change"事件
- View 收到"change"事件后,更新页面
app.js
import React, {Component} from 'react'
import store from './store'
import dispatcher from './dispatcher'
class App extends Component {
constructor(props) {
super(props)
this.state = store.getState()
this.handleInputChange = this.handleInputChange.bind(this)
this.handleStoreChange = this.handleStoreChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
store.on('change', this.handleStoreChange)
}
render() {
return (
<div>
<div>
<input type="text"
value={this.state.inputValue}
onChange={this.handleInputChange}
/>
<button onClick={this.handleSubmit}>提交</button>
</div>
<ul>
{
this.state.list.map((item,index) => (
<li key={index}>{ item }</li>
))
}
</ul>
</div>
)
}
handleInputChange(e) {
const action = {
type: 'CHANGE_INPUT',
value: e.target.value
}
dispatcher.dispatch(action)
}
handleStoreChange() {
this.setState(store.getState())
}
handleSubmit() {
const action = {
type: 'ADD_ITEM'
}
dispatcher.dispatch(action)
}
}
export default App
dispatcher.js
import { Dispatcher } from 'flux'
import store from './store'
const dispatcher = new Dispatcher()
dispatcher.register((action) => {
if(action.type === 'CHANGE_INPUT') {
store.changeInputValue(action.value)
}
if(action.type === 'ADD_ITEM') {
store.addItem()
}
})
export default dispatcher
store.js
import { EventEmitter } from 'events'
const store = Object.assign({
state: {
list: [],
inputValue: ''
},
getState() {
return this.state
},
changeInputValue(value) {
this.state.inputValue = value
this.emit('change')
},
addItem() {
this.state.list.push(this.state.inputValue)
this.state.inputValue = ''
this.emit('change')
}
}, EventEmitter.prototype)
export default store