而不是嵌套结构
export interface BlogContent {
id: string;
header: string;
tags: string[];
title: string;
actualContent: ActualContent[]; <------ NESTED
}
您应该处于正常化状态。
例如在这里你应该有类似的东西:
// this should be into your store
export interface BlogContents {
byId: { [key: string]: BlogContent };
allIds: string[];
}
// this is made to type the objects you'll find in the byId
export interface BlogContent {
id: string;
// ...
actualContentIds: string[];
}
// ----------------------------------------------------------
// this should be into your store
export interface ActualContents {
byId: { [key: string]: ActualContent };
allIds: string[];
}
export interface ActualContent {
id: string;
// ...
}
因此,如果您尝试填充您的商店,它看起来像这样:
const blogContentsState: BlogContents = {
byId: {
blogContentId0: {
id: 'idBlogContent0',
// ...
actualContentIds: ['actualContentId0', 'actualContentId1', 'actualContentId2']
}
},
allIds: ['blogContentId0']
};
const actualContentState: ActualContents = {
byId: {
actualContentId0: {
id: 'actualContentId0',
// ...
},
actualContentId1: {
id: 'actualContentId1',
// ...
},
actualContentId2: {
id: 'actualContentId2',
// ...
}
},
allIds: ['actualContentId0', 'actualContentId1', 'actualContentId2']
};
在您的逻辑或视图中(例如使用 Angular),您需要嵌套结构,以便可以迭代数组,因此,您不想迭代 ID 的字符串数组。相反你会喜欢actualContent: ActualContent[];
.
为此,您创建一个selector
。每次您的商店发生变化时,您的选择器都会启动并生成原始数据的新“视图”。
// assuming that you can blogContentsState and actualContentsState from your store
const getBlogContents = (blogContentsState, actualContentsState) =>
blogContentsState
.allIds
.map(blogContentId => ({
...blogContentsState.byId[blogContentId],
actualContent: blogContentsState
.byId[blogContentId]
.actualContentIds
.map(actualContentId => actualContentsState.byId[actualContentId])
}));
我知道一开始可能需要处理很多事情,我邀请您阅读关于选择器和规范化状态的官方文档 https://redux.js.org/recipes/structuring-reducers/normalizing-state-shape/
当您学习 ngrx 时,您可能想看看我制作的一个名为 Pizza-Sync 的小项目。代码源在Github上 https://github.com/maxime1992/pizza-sync。这是一个我做过类似演示的项目:)。 (您还应该安装Redux 开发工具应用程序 https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd看看商店怎么样)。
如果您有兴趣,我制作了一个仅关注 Redux 和 Pizza-Sync 的小视频:https://youtu.be/I28m9lwp15Y https://youtu.be/I28m9lwp15Y