组件间通信:https://blog.youkuaiyun.com/RuiKe1400360107/article/details/82992506
redux的用法:https://blog.youkuaiyun.com/RuiKe1400360107/article/details/83023732
redux拆分:https://blog.youkuaiyun.com/RuiKe1400360107/article/details/83028105
router路由:https://blog.youkuaiyun.com/RuiKe1400360107/article/details/83053997
一、基本概念
Flux 是一种架构思想,专门解决软件的结构问题。它跟MVC 架构是同一类东西
Flux将一个应用分成四个部分:
- View: 视图层
- Action(动作):视图层发出的消息(比如mouseClick)
- Dispatcher(派发器):用来接收Actions、执行回调函数
- Store(数据层):用来存放应用的状态,一旦发生变动,就提醒Views要更新页面
Flux 的最大特点,就是数据的"单向流动":数据总是"单向流动",任何相邻的部分都不会发生数据的"双向流动"。
- 用户访问 View
- View 发出用户的 Action
- Dispatcher 收到 Action,要求 Store 进行相应的更新
- Store 更新后,发出一个"change"事件
- View 收到"change"事件后,更新页面
二、详细介绍
1.View
举个Demo:
// index.jsx
var React = require('react');
var ReactDOM = require('react-dom');
var MyButtonController = require('./components/MyButtonController');ReactDOM.render(
<MyButtonController/>,
document.querySelector('#example')
);
上面代码中,,组件的名字不是 MyButton
,而是 MyButtonController
。采用的是 React 的 controller view 模式。"controller view"组件只用来保存状态,然后将其转发给子组件
MyButton
只有一个逻辑:就是一旦用户点击,就调用this.crateNewItem
方法,向Dispatcher发出一个Action。
createNewItem: function (event) {
ButtonActions.addNewItem('new item');
}
上面代码中,调用createNewItem
方法,会触发名为addNewItem
的Action
2.Action
每个Action都是一个对象,包含一个actionType
属性(说明动作的类型)和一些其他属性(用来传递数据)
在如下Demo里面,ButtonActions
对象用于存放所有的Action。ButtonActions.addNewItem
方法使用AppDispatcher
,把动作ADD_NEW_ITEM
派发到Store
// actions/ButtonActions.js
var AppDispatcher = require('../dispatcher/AppDispatcher');var ButtonActions = {
addNewItem: function (text) {
AppDispatcher.dispatch({
actionType: 'ADD_NEW_ITEM',
text: text
});
},
};
3.Dispatcher
Dispatcher的作用是将Action派发到Store。相当于路由器,负责在 View 和 Store 之间,建立 Action 的正确传递路线。
注意!Dispatcher 只能有一个,而且是全局的
Facebook官方的 Dispatcher 实现输出一个类,你要写一个AppDispatcher.js
,生成 Dispatcher 实例:
/AppDispatcher.js
var Dispatcher = require('flux').Dispatcher;
module.exports = new Dispatcher();
AppDispatcher.register()
方法用来登记各种Action的回调函数,Dispatcher收到ADD_NEW_ITEM
动作,就会执行回调函数,对ListStore
进行操作。注意,!Dispatcher 只用来派发 Action,不应该有其他逻辑:
// dispatcher/AppDispatcher.js
var ListStore = require('../stores/ListStore');AppDispatcher.register(function (action) {
switch(action.actionType) {
case 'ADD_NEW_ITEM':
ListStore.addNewItemHandler(action.text);
ListStore.emitChange();
break;
default:
// no op
}
})
4.Store
Store 保存整个应用的状态。它的角色有点像 MVC 架构之中的Model
以下Demo 中,有一个ListStore,所有数据都存放在那里。ListStore.items
用来保存条目,ListStore.getAll()
用来读取所有条目,ListStore.emitChange()
用来发出一个"change"事件。由于 Store 需要在变动后向 View 发送"change"事件,因此它必须实现事件接口
// stores/ListStore.js
var ListStore = {
items: [],
getAll: function() {
return this.items;
},
addNewItemHandler: function (text) {
this.items.push(text);
},
emitChange: function () {
this.emit('change');
}
};
module.exports = ListStore;