gpt4 book ai didi

javascript - 如何使用react/flux设置回调

转载 作者:行者123 更新时间:2023-12-02 15:21:28 25 4
gpt4 key购买 nike

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

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

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

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

最佳答案

您应该在操作创建者中使用 Promise,并仅在从 API 调用返回数据后分派(dispatch)操作。

示例

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
})
}

这就是使用 superagent-promise 进行 API 调用的方式:

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 调用返回后才分派(dispatch)操作。一旦商店收到操作,您就可以调用 updateSortWeek() 函数。

关于javascript - 如何使用react/flux设置回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34007445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com