在组件中如何等待操作结果来调用其他操作?

时间:2016-06-22 17:19:54

标签: javascript reactjs flux reactjs-flux jsx

我正在为我的应用程序使用React + Flux。一般流程是我将从JSX组件调用action方法,该action方法将调用更新状态并发出change事件的存储,并且状态将在JSX组件中更新。

现在的问题是,我根据他们的工作将动作和存储分成不同的文件(2个动作文件和2个存储文件)。

我可以在JSX组件中编写这种代码吗? (action2.method2()调用正在等待actions1.method1()的结果。如果没有,我该如何改进? method1()和method2()是两个不同的动作方法,因此我们不能在actions1.method1()体内调用actions2.method2(),并且method2也需要访问由method1()更新的状态。

this.getFlux().actions.actions1.method1()
        .then(() => {
          this.getFlux().actions.actions2.method2(this.state.method1UpdatedState);
         })
        .catch((error) => { console.log("error : ", error)} );

1 个答案:

答案 0 :(得分:0)

我建议尽可能简化操作,并将所有业务逻辑移至您的商店。因此,如果您需要store1store2的数据,只需在store1中注入store2作为依赖项,并聆听由action1生成的特定事件你的store2。你肯定应该避免在你的组件中实现这个逻辑。

例如,store2.js看起来应该如何

import store1 from './store1';

store2.dispatchToken = AppDispathcer.register((payload) => {
   var action = payload.action;

   switch(action) {
       case 'ACTION_1':
         AppDispathcer.waitFor([store1.dispatchToken]);
         let data = store1.getDataFromAction1();
         // ... here you can update store2 data
         // ... and call store2.emitChange();
         break;
   }

});
相关问题