Promise.all处于Redux动作和更新状态

我有两个主要终点;部门和员工。部门端点仅返回部门标识和名称。员工端点返回员工ID和部门ID。因此,如果我想获取员工的详细信息,例如名字,姓氏等,则需要将员工ID添加到“员工”端点。

我不知道我的逻辑是否正确,但是我认为我需要获取每个员工的信息才能在屏幕上呈现他们的详细信息。因此,我尝试使用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;
  }
};
ooxiaoping 回答:Promise.all处于Redux动作和更新状态

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

不是将整个响应分配给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

本文链接:https://www.f2er.com/2981542.html

大家都在问