首页 > 解决方案 > 动作创建者中的循环:“动作必须是普通对象。使用自定义中间件进行异步动作”

问题描述

即使一切似乎都在我的动作创建者中返回了一个动作,我也遇到了这个错误。我必须使用 for 循环来请求数组中的每个项目。看起来我Promise.all的不工作,也许?

有任何想法吗?

index.js

const store = createStore(
    allReducers,
    compose(
        applyMiddleware(thunk),
        window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
    )
);

动作.js

export const searchPeople = (clientAdress, skill, collaborators) => {
  const filteredCollabs = collaborators.filter(collab => collab.skills.includes(skill));
  let collab;
  let origin = "";
  let mode = "";
  let promises = [];
  for (let i = 0; i < filteredCollabs.length; i++) {
    collab = filteredCollabs[i];
    origin = `${filteredCollabs[i].latitude},${filteredCollabs[i].longitude}`;
    mode = `${filteredCollabs[i].mode}`;
    let promise = dispatch => axios
      .get(`https://maps.googleapis.com/maps/api/distancematrix/json?origins=${origin}&destinations=${clientAdress}&region=FR&mode=${mode}&key=${config.gmap.key}`)
      .then(response => dispatch({
        type: "SET_DURATION",
        collab,
        duration: response.data.rows[0].elements[0].duration.text
      }))
      .catch(err => dispatch({
        type: "ERROR",
        err,
      }));
    promises.push(promise);
  }

  function everythingIsDone() {
    return dispatch => Promise.all(promises)
      .then(values => dispatch({
        type: "DONE",
        values
      }))
      .catch(err => dispatch({
        type: "ERROR",
        err
      }))
  }

  everythingIsDone();
}

提前非常感谢!

标签: asynchronousreduxaction

解决方案


推荐阅读