FLux产生的原因
在实际项目工作中,伴随着应用程序的扩展,组件的层层嵌套,运用状态提升来管理数据变得不在优雅并且繁重,Flux就像就一个数据心脏,将数据进行汇集,并通过特殊的定义渠道将数据运送到你项目的奇经八脉.
组成部分
- Store
1:数据中心,存放了组件所需要渲染的数据(甚至组件的状态—–显示或者隐藏)
2:定义数据获取的方法,操作数据的方法
const EventEmitter = require('events').EventEmitter;
const assign = require('object-assign');
const ListStore = assign({}, EventEmitter.prototype, {
items: [],
getAll() {
return this.items;
},
addNewItemHandler(text) {
this.items.push(text);
},
reduceNewItemHandler(){
this.items.pop();
},
emitChange () {
this.emit('change');
},
addChangeListener(callback) {
this.on('change', callback);
},
addChangeListener(callback) {
this.on('change', callback);
},
removeChangeListener(callback) {
this.removeListener('change', callback);
}
});
- Dispatcher
事件分发器—将active事件进行分发
该模块中应只包含事件分发的逻辑
const AppDispatcher = new Dispatcher();//创建Dispatcher实例
AppDispatcher.register((action)=>{
switch(action.type) {
case 'ARRAY_ADD':
ListStore.addNewItemHandler(action.text);
ListStore.emitChange();
break;
case 'ARRAY_REDUCE':
ListStore.reduceItemHandler();
ListStore.emitChange();
break;
}
})
- Action
作为Dispatcher分发的对象
const ButtonActions = {
addNewItem(text) {
AppDispatcher.dispatch({
actionType: 'ARRAY_ADD',
text: text
});
},
reduceItem() {
AppDispatcher.dispatch({
actionType: 'ARRAY_REDUCE'
});
}
};
- View
视图层—–Dispatcher的触发器
import React, { Component } from 'react';
class MyButtonController extends Component{
getInitialState() {
return {
items: ListStore.getAll()
};
}
componentDidMount() {
ListStore.addChangeListener(this._onChange);
}
componentWillUnmount() {
ListStore.removeChangeListener(this._onChange);
}
_onChange() {
this.setState({
items: ListStore.getAll()
});
}
createNewItem=()=> {
ButtonActions.addNewItem('内容');
}
reduceItem=()=> {
ButtonActions.reduceItem();
}
render() (
<MyButton
items={this.state.items}
onAddClick={this.createNewItem}
onReduceClick={this.reduceItem}
/>
);
}
});
const MyButton = (props)=> {
let items = props.items;
let itemHtml = items.map((listItem, i)=>{
return <li key={i}>{listItem}{i}</li>;
});
return <div>
<ul>{itemHtml}</ul>
<button onClick={props.onAddClick}>增加</button>
<button onClick={props.onReduceClick}>减少</button>
</div>;
};
Flux 的最大特点,就是数据的”单向流动”。
- 用户访问 View
- View 发出用户的 Action
- Dispatcher 收到 Action,要求 Store 进行相应的更新
- Store 更新后,发出一个”change”事件
- View 收到”change”事件后,更新页面