Promise.all 在 Redux 操作和更新状态

Promise.all in Redux action and update state

我有两个主要终点;部门和员工。部门端点 returns 只有部门 ID 和名称。员工端点 return 员工 ID 和部门 ID。因此,如果我想获取员工详细信息,例如名字姓氏等,我需要将员工 ID 添加到 Employees 端点。

我不知道我的逻辑是否正确,但我认为我需要获取每个员工以在屏幕上呈现他们的详细信息。因此,我尝试使用 Promise.all 然后更新我的状态一次, 但不知何故我的状态只存储一个值 (一个员工对象)但有超过 1000雇员。

这是我的步骤: 首先,向主要的 Employees 端点发出请求以获取所有员工 (fetchEmployees),然后调度 fetchEmployeeOneByOne 并在此方法中在 Promise.all 中发出请求,最后调度 updateEmployees 以设置状态。

操作

const UPDATE_EMPLOYEES = UPDATE_EMPLOYEES
export const fetchEmployees = () => dispatch => {
  return fetch(EMPLOYEE_MAIN_URL)
    .then(res => {
      if (res.ok) {
        return res;
      }
    })
    .then(res => res.json())
    .then(employees => dispatch(fetchEmployeeOneByOne(employees)))
    .catch(error => dispatch(console.log(error)));
};

export const fetchEmployeeOneByOne= employees => dispatch => {
  Promise.all(
    employees.map(employee =>
      fetch(EMPLOYEE_MAIN_URL + '/' + employee.id)
        .then(res => {
          if (res.ok) {
            return res;
          }
        })
        .then(res=> res.json())
        .then(employee => dispatch(updateEmployees(employee)))
        .catch(error => dispatch(console.log(error)))
    )
  );
};

export const updateEmployees = employee => ({
  type: UPDATE_EMPLOYEES,
  payload: employee
});

减速器

export const Departments = (
  state = {
    departments: [],
    employees: [],
  },
  action
) => {
  switch (action.type) {
    case 'UPDATE_EMPLOYEES':
     return { ...state, employees: action.payload };
    default:
      return state;
  }
};

在每个 Promise 解析和 reducer 循环中,您都在覆盖状态,因此最终结果只有一名员工。

与其将整个响应分配给 employees 字段,不如将其放入 employees 数组中:

case 'UPDATE_EMPLOYEES':
   return { 
      ...state, 
      employees: [...state.employees, action.payload],
   };

看起来您可能想要汇总您的员工,然后在 Promise.all 解决后分派操作:

Promise.all(
  employees.map(employee =>
    fetch(EMPLOYEE_MAIN_URL + '/' + employee.id)
      .then(res => {
        if (res.ok) {
          return res;
        }
      })
      .then(res=> res.json())
      .catch(error => dispatch(console.log(error)))
  )
).then(employees => dispatch(updateEmployees(employees));

否则,如果您只想在每个员工从您的获取请求中派遣他们,就没有理由使用 Promise.all