在redux-thunk中调用一个异步函数内的另一个函数
我正在构建一个Reaction应用程序,并使用redux-thunk进行异步操作。我有两个函数getActivities()
和createActivity()
,我想在成功调用后者后调用前者。但是如果我将getActivities()
放在createActivity()
的then
块中,它就不会被调用(这通过没有看到我放在getActivities()
中的console.log()来证明)。下面是两个函数:
export const getActivities = () => dispatch => {
console.log('again');
return axios.get(ENV.stravaAPI.athleteActivitiesBaseEndPoint, autHeaders)
.then(resp => {
dispatch({type: actions.GET_ACTIVITIES, activities: resp.data})
})
.catch(err => {
if(window.DEBUG)console.log(err);
})
};
export const createActivity = data => dispatch => {
dispatch(setLoadingElement('activityForm'));
return axios.post(URL, null, autHeaders)
.then(resp => {
if (resp.status === 201) {
dispatch(emptyModal());
}
// I WANT TO CALL getActivities() HERE
dispatch(unsetLoadingElement('activityForm'));
})
.catch(err => {
if(window.DEBUG) console.log(err.response.data.errors);
dispatch(unsetLoadingElement('activityForm'));
});
};
如何在另一个内部调用?
解决方案
要从一个操作创建者内部调用另一个操作,只需dispatch
该操作,如dispatch(getActivities())
export const createActivity = data => dispatch => {
dispatch(setLoadingElement('activityForm'));
return axios.post(URL, null, autHeaders)
.then(resp => {
if (resp.status === 201) {
dispatch(emptyModal());
}
dispatch(getActivities());
dispatch(unsetLoadingElement('activityForm'));
})
.catch(err => {
if(window.DEBUG) console.log(err.response.data.errors);
dispatch(unsetLoadingElement('activityForm'));
});
};
相关文章