目前,我正在构建一个严重依赖API调用的应用程序。api调用是在Redux操作中使用Thunk中间件完成的,如下所示:
export const brand_fetchAll = () => {
return dispatch => {
fetch(apiURL+'brand')
.then(response => {return response.json();})
.then(content => {
dispatch({
type: 'BRAND_STORE_ALL',
content
})
})
.catch(error => console.log(error))
}}在我的组件中,我首先通过单独的操作获取数据。在此之后,我将打开一个编辑器:
// A component method
editModeOn(){
// Fetch data
this.props.dispatch(campaign_fetchAll());
this.props.dispatch(brand_fetchAll());
// Open editor
this.props.dispatch(page_editModeOn());
}现在编辑器在api调用完成之前打开,因此没有显示任何数据。可以在操作中链接分派,但我希望保持模块化,这样就不必创建数百个自定义API调用。理想情况下,我想要的是使用诸如promises之类的东西来链接它们:
// A component method
editModeOn(){
this.props.dispatch(campaign_fetchAll().then(brand_fetchAll()).then(page_editModeOn());
}不幸的是,我还没有让它工作。我希望有人能帮帮我。如果您需要更多信息,我很乐意提供给您。更好的想法也非常受欢迎:)
提前感谢!
发布于 2018-11-02 22:23:09
回调函数是你的一个选择吗?
因此,将您的代码更新为;
export const brand_fetchAll = (callback) => {
return dispatch => {
fetch(apiURL+'brand')
.then(response => {return response.json();})
.then(content => {
dispatch({
type: 'BRAND_STORE_ALL',
content
});
callback();
})
.catch(error => console.log(error))
}}
// A component method
editModeOn(){
// Fetch data
this.props.dispatch(campaign_fetchAll());
this.props.dispatch(brand_fetchAll(() => {
// Open editor
this.props.dispatch(page_editModeOn());
}));
}您正在将回调链接到api调用成功的末尾,但是,您并没有紧密地耦合它是什么,因为您是根据用法传递它的。
https://stackoverflow.com/questions/53120292
复制相似问题