【发布时间】:2018-09-15 21:13:15
【问题描述】:
实际上我正在使用 NGRX(Redux for Angular)。一开始我已经开始将我的实体作为数组存储在我的状态中。在阅读了一些文章后,我想将我的实体存储为哈希值,而我认为使用 id 访问实体实体而不是过滤数组会更高效。
但我实际上不确定这样做是否正确。
请随时在此处查看我的(工作 - 但最佳实践?)示例: Ngrx Articles Sample
在articles.component 中,您会找到articleReducer 和ArticlesComponent,它们将使用商店来获取所有文章并获取一篇具体文章。
对于每个不确定的部分,我都会用 QUESTION x - ... 发表评论
如果您不想查看完整示例,请查看以下问题片段:
问题 0:
export const initialState: ArticleState = {
foo: 'bar',
articlesById: [], // QUESTION 0: What is a good usecase to hold an array with the id's when Object.keys(hash) will give the same?
articleEntities: {}
}
问题 1 + 2:
case GET_ALL_ARTICLES: {
// QUESTION 1: is this a good choice? Or is there a better alternative to create the hash?
const articleHash: { [id: number]: Article} = {};
action.payload.forEach(article => articleHash[article.id] = article);
return {
...state,
// QUESTION 2: is this a good choice? Or is there a better alternative?
articlesById: action.payload.map(article => article.id),
articleEntities: articleHash
}
}
问题 3:
// QUESTION 3 - Getting all articleEntities as Array for ngFor : is this a good choice? Or is there a better alternative?
this.articles$ = this.store.pipe(
select('articles', 'articleEntities'),
map(entities => Object.keys(entities).map(id => entities[id]))
);
问题 4:
const givenIdByRouterMock = 2;
// QUESTION 4 - Getting one concrete Article for given id : is this a good choice? Or is there a better alternative?
this.article$ = this.store.pipe(
select('articles', 'articleEntities'),
map(entities => entities[givenIdByRouterMock])
);
如果我将使用新操作更新某些文章(例如 id 为 2),我希望包含该文章的组件将被更新。
这是有效的变体还是有更好的选择、解决方案?随意将 stackblitz 示例与其他变体/代码 sn-ps 分叉。
谢谢!
【问题讨论】: