React Reflux
概念 Reflux是根据React的flux创建的单向数据流类库。 ╔═════════╗ ╔════════╗ ╔═════════════════╗ ║ Actions ║──────>║ Stores ║──────>║ View Components ║ ╚═════════╝ ╚════════╝ ╚═════════════════╝ ^ │ └──────────────────────────────────────┘ 代码看起来像这样的: var TodoActions = Reflux.createActions([
'addItem'
]);
var TodoStore = Reflux.createStore({
items: [1,2],listenables: [TodoActions],onAddItem: function (model) {
$.post('/server/add',{data: model},function (data) {
this.items.unshift(data);
this.trigger(this.items);
});
}
});
var TodoComponent = React.createClass({
mixins: [Reflux.listenTo(TodoStore,'onStatusChange')],getInitialState: function () {
return {list: []};
},onStatusChange: function () {
this.setState({list: TodoStore.items});
},render: return (
<div>
{this.state.list.map(function (item) {
return <p>{item}</p>
})}
</div>
)
}
});
React.render(<TodoComponent />,document.getElementById('container'));
同React Flux比较相同点
不同点
创建Actionvar statusUpdate = Reflux.createAction(options);
返回值是一个函数,调用这个函数就会触发相应的事件,在store中监听这个函数,并作相应的处理 var addItem = Reflux.createAction();
var TodoStore = Reflux.createStore({
init: this.listenTo(addItem,152)">'addItem');
},addItem: function (model) {
console.log(model);
}
});
addItem({name: 'xxx'});
创建多个Actionvar TodoActions = Reflux.createActions([
'addItem',152)">'deleteItem'
]);
store监听actions的行为: 'deleteItem'
]);
this.listenTo(TodoActions.addItem,152)">'addItem');
this.listenTo(TodoActions.deleteItem,152)">'deleteItem');
},0)">function (model) {
console.log(model)
},deleteItem:function(model){
console.log(model);
}
});
TodoActions.addItem({name:'xxx'});
TodoActions.deleteItem({name:'yyy'});
异步Action真实的应用场景中,几乎所有的操作都会向后端请求,而这些操作都是异步的,Reflux也提供了相应的Promise接口 var getAll = Reflux.createAction({asyncResult:true});
例如获取全部数据: var getAll = Reflux.createAction({asyncResult: true});
this.listenTo(getAll,152)">'getAll');
},getAll: function (model) {
$.get('/all',0)">function (data) {
if (data) {
getAll.completed(data);
} else {
getAll.failed(data);
}
});
}
});
getAll({name: 'xxx'})
.then(function (data) {
console.log(data);
})
.catch(function (err) {
throw err;
});
Action hooksReflux为每个action都提供了两个hook方法
情景一: var addItem = Reflux.createAction({
preEmit: function (params) {
console.log('preEmit:' + params);
},shouldEmit: 'shouldEmit:' + params);
}
});
'addItem:' + params);
}
});
addItem('xxx');
控制台打印
$ preEmit:xxx
$ shouldEmit:xxx
情景二: 'preEmit:' + params);
return 324;
},152)">'shouldEmit:' + params);
return true;
}
});
'xxx');
控制台打印
$ preEmit:xxx
$ shouldEmit:324
$ addItem:324
Action Methods当需要给所有的action添加公用方法时,可以这么干: Reflux.ActionMethods.print = function (str) {
console.log(str);
};
'addItem:' + params);
}
});
addItem.print('xxx');
trigger、triggerAsync和triggerPromise直接调用addItem()实际上是调用trigger或者triggerAsync或者triggerPromise,它们区别在于 var addItem = Reflux.createAction(); addItem(); #默认调用triggerAsync,相当于addItem.triggerAsync()
var addItem = Reflux.createAction({sync:true});addItem(); #默认调用trigger,相当于addItem.trigger()
var addItem = Reflux.createAction({asyncResult:true});addItem();#默认调用triggerPromise,相当于addItem.triggerPromise()
trigger和triggerAsync区别在于: triggerAsync = setTimeout(function () {
trigger()
},152)">0);
trigger和triggerPromise区别在于,triggerPromise的返回值是promise 创建StoreStore可以响应Action的行为,并同服务器交互。 监听单个Action在init方法中添加监听处理 'xxx'}); 监听多个Action作死写法console.log(model);
},deleteItem: console.log(model);
}
});
TodoActions.addItem({name: 'xxx'});
TodoActions.deleteItem({name: 'yyy'});
两个action的时候在init里写了两遍监听处理方法,如果有十个甚至多个的话,写起来就像这样的: 'item1',152)">'item2',152)">'item3',152)">'item4',152)">'item5',152)">'item6',152)">'item7',152)">'item8',152)">'item9',152)">'item10'
]);
this.listenTo(TodoActions.item1,152)">'item1');
this.listenTo(TodoActions.item2,152)">'item2');
this.listenTo(TodoActions.item3,152)">'item3');
this.listenTo(TodoActions.item4,152)">'item4');
this.listenTo(TodoActions.item5,152)">'item5');
this.listenTo(TodoActions.item6,152)">'item6');
this.listenTo(TodoActions.item7,152)">'item7');
this.listenTo(TodoActions.item8,152)">'item8');
this.listenTo(TodoActions.item9,152)">'item9');
this.listenTo(TodoActions.item10,152)">'item10');
},item1: console.log(model);
}
});
TodoActions.item1({name: 'xxx'});
TodoActions.item2({name: 'yyy'});
listenToMany还好Reflux给我们提供了listenToMany方法,避免重复劳动: this.listenToMany(TodoActions);
},onItem1: 处理方法只需让action的标识首字母大写并加上on就可以了。
同组件结合 前面说了,Action、Store和组件这三者是通过事件机制响应变化的,构建组件的时候首先需要监听Store的状态。 'getAll'
]);
2,152)">3],onGetAll: this.trigger(this.items);
}
});
基本var TodoComponent = React.createClass({
getInitialState: function (list) {
this.setState({list: list});
},componentDidMount: function () {
this.unsubscribe = TodoStore.listen(this.onStatusChange);
TodoActions.getAll();
},componentWillUnmount: function () {
this.unsubscribe();
},0)">return <p>{item}</p>
})}
</div>
)
}
});
React.render(<TodoComponent />,152)">'container'));
这里有两点需要注意:
Mixinsvar TodoComponent = React.createClass({ mixins: [Reflux.ListenerMixin],0)">return <p>{item}</p> })} </div> ) } }); React.render(<TodoComponent />,152)">'container')); Reflux.listenTofunction () {
TodoActions.getAll();
},152)">'container'));
Reflux.connectvar TodoComponent = React.createClass({
mixins: [Reflux.connect(TodoStore,152)">'list')],sans-serif; font-size:14px; line-height:22.4px"> 数据会自动更新到state的list当中。
|