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

原学程将引见在redux-thunk中挪用1个异步函数内的另外一个函数的处置办法,这篇学程是从其余处所瞅到的,而后减了1些海外法式员的疑问与解问,愿望能对于您有所赞助,佳了,上面开端进修吧。

在redux-thunk中调用一个异步函数内的另一个函数 教程 第1张

成绩描写

我正在建立1个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 === 二0一) {
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'));
 });
};

怎样在另外一个外部挪用?

推举谜底

要从1个操纵创立者外部挪用另外一个操纵,只需dispatch该操纵,如dispatch(getActivities())

export const createActivity = data => dispatch => {

 dispatch(setLoadingElement('activityForm'));
 return axios.post(URL, null, autHeaders)
  .then(resp => {
if (resp.status === 二0一) {
 dispatch(emptyModal());
}
dispatch(getActivities());
dispatch(unsetLoadingElement('activityForm'));
  })
  .catch(err => {
if(window.DEBUG) console.log(err.response.data.errors);
dispatch(unsetLoadingElement('activityForm'));
  });
 };

佳了闭于在redux-thunk中挪用1个异步函数内的另外一个函数的学程便到这里便停止了,愿望趣模板源码网找到的这篇技巧文章能赞助到年夜野,更多技巧学程不妨在站内搜刮。