在 NgRx 应用程序中对对象使用 Array.reduce 函数

Using Array.reduce function with objects in a NgRx application

在一个 NgRx Angular 5 项目中,有一个 reduce 函数的用法我不太明白。我会很感激一些帮助

代码基本上迭代对象数组,数组如下所示:

[{
   id: '0',
   message: 'work',
   done: false
 },
 {
   id: '1',
   message: 'movie',
   done: false
 },
 {
   id: '2',
   message: 'Play',
   done: false
 }]

在我的 NgRx reducer 中,有以下代码块:

case todosAction.FETCH_TODO_SUCCESS: {
  return {
    ...state,
    //action.payload contains above array of objects
    datas: action.payload.reduce((accumulateur, iteration) => {
      accumulateur[iteration.id] = iteration;
      return accumulateur;
    }, { ...state.datas }),
    loading: false,
    loaded: true,
    error: null 
  };
}

我使用的状态是这样的:

export interface TodoState {
  datas: {
    [todoId: string]: Todo
  }
  loading: boolean;
  loaded: boolean;
  error: any;
}

我们在这里使用 reduce 函数将原始源(对象数组)转换为实体(一个键,它是与 todo 对象关联的 id)。 我明白我们为什么使用这个函数的原因,但我不明白它的内部代码:

action.payload.reduce((accumulateur, iteration) => {
          accumulateur[iteration.id] = iteration; // <-- AS FAR AS I UNDERSTAND, ACCUMULATOR IS NOT AN ARRAY, HOW CAN WE ACHIEVE SUCH A THING
          return accumulateur;
        }, { ...state.datas })

提前感谢您帮助我阐明这一点。

假设

state.datas 等于:

{
  '0': {
    id: '0',
    message: 'Hello',
    done: false
  }
}

action.payload 等于

[{
  id: '1',
  message: 'World',
  done: false
}]

reducer returns 之后你会得到

{
  '0': {
    id: '0',
    message: 'Hello',
    done: false
  },
  '1': {
    id: '1',
    message: 'World',
    done: false
  }
}

需要注意的重要一点是id是一个字符串。您可以拥有一个键为 '0' 的对象。这与使用任何其他字符串没有什么不同。