INITIALIZE_APP と呼ばれるアクションを開始する初期化関数を作成し、このアクションの受信時に必要なストアに初期化を実行させます。ルートの反応コンポーネントをレンダリングする前に、すべてのストアが初期化を完了するのを待ちます。
//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;
INITALIZE_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;
}
ルートの反応コンポーネントを実行する前に、初期化関数を呼び出します。
//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"));
});