编写一个初始化函数,该函数启动一个名为 INITIALIZE_APP 的操作,并让必要的商店在接收到该操作时执行初始化。等待所有 store 完成初始化,然后再渲染根 react 组件。
//initialize.js
var initialize = function() {
var dispatchToken = AppDispatcher.register(payload => {
var action = payload.action;
if (action.type !== AppConstants.ActionTypes.INITIALIZE_APP) {
return;
}
// wait for all the stores to initialize before rendering
var tokens = [
CustomerStore,
NavigationStore,
].map(store => store.dispatchToken);
AppDispatcher.waitFor(tokens);
AppDispatcher.unregister(dispatchToken);
});
InitializeAppActions.initialize(); // Creates INITIAL_LOAD action
};
module.exports = initialize;
为 INITALZE_APP 定义了一个操作
// InitializeAppActions.js
var InitializeAppActions = {
initialize() {
AppDispatcher.handleViewAction({
type: ActionTypes.INITIALIZE_APP,
});
return true;
},
};
module.exports = InitializeAppActions;
商店监听 INITIALIZE_APP 动作
//CustomerStore.js
CustomerStore.dispatchToken = AppDispatcher.register(function(payload) {
var action = payload.action;
switch (action.type) {
//Called when the app is started or reloaded
case ActionTypes.INITIALIZE_APP:
initializeCustomerData();
break;
}
在执行根 react 组件之前调用初始化函数。
//app.js
var initialize = require("./initialize.js");
//initialize the stores before rendering
initialize();
Router
.create({
routes: AppRoutes,
})
.run(function(Handler) {
React.render( <Handler/>, document.getElementById("react-app"));
});