【问题标题】:how to setup a callback using react/flux如何使用 react/flux 设置回调
【发布时间】:2016-03-04 14:39:37
【问题描述】:

我目前正在学习 react/flux/alt。我有一个带有以下 componentDidMount 的页面:

componentDidMount() {
  LeaderBoardStore.listen(this.onChange);
  LeaderBoardActions.getCurrentWeek();
  LeaderBoardActions.getSeason();
  LeaderBoardActions.updateSortWeek(this.state.currentWeek);    
  LeaderBoardActions.getLeaders(this.query());
}

我遇到的问题是所有操作都是异步的。也就是说,他们调用了一个在触发回调之前不会响应的 api。这是在 Actions 中。

我的问题是如何使用 Actions 获取当前周并在 updateSortWeek() 之前等待它处理

【问题讨论】:

  • getCurrentWeek() 是什么样的?您可能应该为此使用promises
  • getCurrentWeek() { this.dispatch(); api.get('/week', (err, res) => { if (err) { this.actions.updateCurrentWeek(''); } else { this.actions.updateCurrentWeek(res.body.week); } } ); }
  • 好的,所以在api.get的回调中是你要调用updateSortWeek()的地方

标签: javascript reactjs reactjs-flux


【解决方案1】:

您应该在动作创建者中使用 Promise,并仅在您从 API 调用中取回数据后才调度动作。

例子

getCurrentWeek: function() {
  // Make the API Call and get back the response (data)
  ApiUtils.getWeek().then(function(data){
  // Dispatch an action
  AppDispatcher.dispatch({
    type: ActionTypes.GET_WEEK,
    data: data, 
  });
  }).catch(function(err){
    // Handle the error
  })
}

这就是 API 调用使用 superagent-promise 的样子:

getWeek: function() {
  return superagent
      .get( url )
      .set('Accept', 'application/json')
      .query({
        // Query
      })
      .end()
      .then(function(res) {
        var week = res.body;
        if ( !week ) {
          return Promise.reject( new Error("Error") );
        } else {
          return week;
        }
      });

},

这样,您只有在从 API 调用返回后才调度操作。一旦商店获得操作,您就可以调用您的updateSortWeek() 函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-22
    • 2015-11-19
    • 1970-01-01
    • 2016-09-16
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    • 2016-12-05
    相关资源
    最近更新 更多