您的位置:首页 > Web前端 > React

react爬坑记16---reflux

2016-05-05 20:58 603 查看
原文:https://segmentfault.com/a/1190000002793786

flux:

user–>actions–>dispatcher–>stores–view Components

reflux:

user–>actions–>stores–>view Components

reflux code:

var TodoActions = Reflux.createAction([
"addItem"
]);

var TodoStore = Reflux.createStore({
items: [1, 2],
listenables: [TodoActions],
onAddItem: function(model) {
$.post('/server/add', {data: model}, funciotn(data) {
this.items.unshift(data);//向头部添加数据
this.trigger(this.items);//?
});
}
});

var TodoComponnet = React.createClass({
mixins:[Reflux.listenTo(TodoStore, "onStatusChange")],
getInitialState: function() {
return {
list: []
};
},
onStatusChange: function() {
this.setState({list: TodoStore.items})
},
render:funcion() {
return(
<div>
{this.state.list.map(function (item){
return <p>{item}</P>
})}
</div>
)
},
});
React.render(<TodoComponent/>, document.getElementById("container"));


与flux比较

相同点:有actions、stores,单项数据流

不同点:通过内部拓展actions的行为,移除了单例的dispatcher

stores可以监听actions的行为,无需进行冗杂的switch判断

stores可以相互监听,可以进行进一步的数据聚合操作,类似于map/reduce

waitFor被连续和平行的数据流所代替

创建Action

var statusUpdate = Reflux.createActions(options)


返回值是一个函数,调用这个函数就会触发相应的事件,在store中监听这个函数,并做相应的处理。

var addItem = Reflux.createAction();
var TodoStore = Reflux.createStore({
init: function() {
this.listenTo(addItem, 'addItem');
},
addItem: function(model) {
console.log(model);
}
});
addItem({name: 'XXX'});


创建多个Action

var TodoActions = Reflux.createActions({
'addItem',
'deleteItem'
});


store监听actions的行为:

var TodoActions = Reflux.createActions({
'addItem',
'deleteItem'
});
var TodoStore = Reflux.createStore({
init: function() {
this.listenTo(TodoActions.addItem, 'addItem');
this.listenTo(TodoActions.deleteItem, 'deleteItem');
},
addItem: function(model){
console.log(model);
},
deleteItem: function(model) {
console.log(model);
}
});
TodoActions.addItem({name:"XXX"});
TodoActions.deleteItem({name:"YYY"});


listenables: (写真实应用的时候采用这种写法)

var TodoActions = Reflux.createActions([
'item1',
'item2',
'item3',
'item4',
'item5',
'item6',
'item7',
'item8',
'item9',
'item10'
]);

var TodoStore = Reflux.createStore({
listenables: [TodoActions],
onItem1: function (model) {
console.log(model);
},
onItem2: function (model) {
console.log(model);
}
});

TodoActions.item1({name: 'xxx'});
TodoActions.item2({name: 'yyy'});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  reactjs