我正在阅读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',name: 'Dan' } }]
可以这种方式归一化 –
{ result: [1,2],entities: { articles: { 1: { id: 1,author: 1 },2: { id: 2,author: 1 } },users: { 1: { id: 1,name: 'Dan' } } } }
规范化的优势是什么?
您可以提取所需状态树的确切部分.
例如 – 您有一个包含有关文章信息的对象数组.如果要从该数组中选择特定对象,则必须遍历整个数组.最坏的情况是数组中不存在所需的对象.为了克服这个问题,我们将数据标准化.
要规范化数据,请将每个对象的唯一标识符存储在单独的数组中.我们将该数组称为结果.
结果:[1,2,3 ..]
并将对象数组转换为以key作为id的对象(请参阅第二个片段).将该对象称为实体.
最终,要访问id为1的对象,只需执行this- entities.articles [“1”].
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。