gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 23:23:36 24 4
gpt4 key购买 nike

在 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 返回后你会得到

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

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

关于javascript - 在 NgRx 应用程序中对对象使用 Array.reduce 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49917371/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com