我正在阅读 Redux Reducers docs也不知道国家正常化会如何运作。示例中的当前状态是这样的:
{
visibilityFilter: 'SHOW_ALL',
todos: [
{
text: 'Consider using Redux',
completed: true,
},
{
text: 'Keep all state in a single tree',
completed: false
}
]
}
您能否提供一个示例,说明如果我们遵循以下内容,上面的内容会是什么样子?
For example, keeping todosById: { id -> todo } and todos: array inside the state would be a better idea in a real app, but we’re keeping the example simple.
最佳答案
这个例子直接来自Normalizr .
[{
id: 1,
title: 'Some Article',
author: {
id: 1,
name: 'Dan'
}
}, {
id: 2,
title: 'Other Article',
author: {
id: 1,
name: 'Dan'
}
}]
可以这样标准化-
{
result: [1, 2],
entities: {
articles: {
1: {
id: 1,
title: 'Some Article',
author: 1
},
2: {
id: 2,
title: 'Other Article',
author: 1
}
},
users: {
1: {
id: 1,
name: 'Dan'
}
}
}
}
标准化有什么好处?
您可以提取状态树中您想要的确切部分。
例如,您有一个对象数组,其中包含有关文章的信息。如果要从该数组中选择特定对象,则必须迭代整个数组。最坏的情况是数组中不存在所需的对象。为了克服这个问题,我们对数据进行标准化。
要标准化数据,请将每个对象的唯一标识符存储在单独的数组中。我们将该数组称为结果
。
结果:[1, 2, 3 ..]
并将对象数组转换为一个以键作为id
的对象(参见第二个片段)。将该对象称为实体
。
最终,要访问 id
1 的对象,只需执行以下操作 - entities.articles["1"]
。
关于reactjs - 在 React Redux 应用程序中规范化状态的示例是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38990984/