我最近在一个同构应用程序中使用Flux架构,并使用react-router来处理应用程序的路由。我的问题是,当路由改变时,如何从外部API加载数据?
的例子:
- http://myapp.com/#/search/:param1/:param2 => show ResultComponent (load data and set state in ResultComponent)
- http://myapp.com/#/detail/:id => show DetailComponent (loaddata and set state in DetailComponent)
据我所知,数据必须在Action中加载。但是我还没有找到一个简明的例子。
触发一个动作
App.js
'use strict';
import React from 'react';
import AppCtrl from './components/app.ctrl.js';
import Actions from './flux/Actions';
import ApiStore from './flux/Api.Store';
window.React = React;
Actions.apiInit();
React.render( <AppCtrl />, document.getElementById('react') );
ApiStore
import Reflux from 'reflux';
import Actions from './Actions';
import ApiFct from './../utils/ws.api.js';
function _apiInit() { ApiFct.init(); }
function _apiInitDone() { ApiFct.getData(); }
function _apiSetData(data) { ApiFct.setData(data); }
var ApiStoreObject = {
listenables: Actions,
apiInit: _apiInit,
apiInitDone: _apiInitDone,
apiSetData: _apiSetData
}
const ApiStore = Reflux.createStore(ApiStoreObject);
export default ApiStore;
Api import Actions from '../flux/Actions';
module.exports = {
socket: {},
init: function() {
this.socket = new Primus();
this.socket.on('server:GotData', this.gotData);
Actions.apiInitDone();
},
getData: function() { this.socket.send('client:GetData', {}); },
gotData: function(data) { Actions.gotData(data); Actions.gotData2(data); },
setData: function(data) { this.socket.send('client:SetData', data); },
};
操作import Reflux from 'reflux';
var apiActions = [
'apiInit',
'apiInitDone',
'apiSetData'
]
var wsActions = [
'gotData',
'gotData2'
]
var actionArray = wsActions.concat(apiActions);
module.exports = Reflux.createActions(actionArray);