在 redux-thunk 中调用另一个异步函数

IT技术 javascript reactjs asynchronous redux-thunk
2021-05-12 12:46:09

我正在构建一个 React 应用程序并使用 redux-thunk 进行异步操作。我有两个函数getActivities()createActivity()我想在成功调用后者后调用前者。但是如果我把放在它的getActivities()里面就不会被调用(这可以通过没有看到我放入的 console.log() 来证明)。下面是两个函数:thencreateActivity()getActivities()

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

我怎样才能在另一个内部调用一个?

2个回答

为了从一个动作创建者内部调用另一个动作,你只需要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'));
        });
 };
getActivites()

确实成功地调用了getActivities(). 但是,它返回一个包含console.log()调用的匿名函数您在此处忽略此返回值。

您必须调度返回的函数以确保它被调用:

dispatch(getActivities())