redux入门 互动版

在线工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器

如何设计state

本小节将具体介绍如何合理设计state

1、设计state注意事项

在 Redux 应用中,所有的 state 都被保存在一个单一对象中。那该如何设计state?

  • 应该尽量使state可以轻松的转化为JSON。
  • 尽可能地把 state 范式化,不存在嵌套
  • 把所有数据放到一个对象里,每个数据以 ID 为主键
  • 把state想象成一个数据库

我们可以通过下面例子做一下比较:

//方式一
[{
  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'
      }
    }
  }
}

像上面例子中的方式二,我们设计state时应该尽可能地遵循范式

2、范式化存储有什么好处呢?

A、假如我们要改变作者姓名,你可以想象如果数据较多我们要修改方式一那简直是场灾难,比较方式二就优雅许多只要修改users[1].name就行

B、可以节省存储空间,避免了数据冗余

C、便于我们拆分reducer,我们后面会提到分割reducer