reactjs - 在 React Redux 应用程序中规范化状态的示例是什么?

标签 reactjs redux state react-redux

我正在阅读 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/

相关文章:

javascript - Angular ui 路由器 : accessing $stateParams on reload

javascript - 在 React 中单击组件外部时更改状态

reactjs - 如何使用 React 惰性/Suspense 代码分割让 webpack-dev-server 停止在内容更改时下载不正确的 block ?

reactjs - 类型 'Element | undefined' 不可分配给类型 'FC<any> | undefined'

javascript - 错误 : Element type is invalid: expected a string (for built-in components) - reactjs

angularjs - 是否可以通过 Angular 中 UI-Router 的 AJAX 请求加载模板?

reactjs - React/Redux 搜索过滤器在您键入时更新应用程序状态

redux - 我应该把用于转换数据的业务逻辑放在哪里 ngrx 存储 : into effects or reducers?

javascript - 如何在 react redux 中添加 protected 路由

javascript - 从动态创建的子组件更改状态 - React