关于 redux real-world example 中的 normalize

About normalize in redux real-world example

example 的 src(UserPage.js):

  const mapStateToProps = (state, ownProps) => {
  // We need to lower case the login due to the way GitHub's API behaves.
  // Have a look at ../middleware/api.js for more details.
  const login = ownProps.params.login.toLowerCase()

  const {
    pagination: { starredByUser },
    entities: { users, repos }
  } = state

  const starredPagination = starredByUser[login] || { ids: [] }
  const starredRepos = starredPagination.ids.map(id => repos[id])
  const starredRepoOwners = starredRepos.map(repo => users[repo.owner])

  return {
    login,
    starredRepos,
    starredRepoOwners,
    starredPagination,
    user: users[login]
  }
}

我注意到有很多像 xxx.ids.map(id => someEntities[id]) 这样的模板,我不确定为什么要将这种模式用于 work.IMO,我会在容器组件中使用像 import { map } from 'lodash'; someList && map(someList, item => {...}) 这样的东西,只是传递 mapStateToProps.

中的实体

那么,有人能解释一下它的用途吗?谢谢。

在 Redux 中规范化数据的标准建议是将数据项存储在对象中,以 ID 作为键,项作为值。但是,对象没有固有的顺序。 (从技术上讲,对象键的迭代顺序 应该 是一致的,但是依赖它作为唯一的排序方式是一种不好的做法。)

因此,仅存储 ID 数组也是标准做法。典型示例可能如下所示:

{
    byId : {
        qwerty : { },
        abcd : { },
        aj42913 : { }    
    },
    items : ["qwerty", "aj42913", "abcd"],
    sorted : ["abcd", "aj42913", "qwerty"],
    selected : ["qwerty", "abcd"]
}

在此示例中,items 包含 所有 个项目 ID,可能按照它们插入的顺序。 sorted 包含某种排序顺序的 ID,而 selected 包含 ID 的子集。

这允许项目本身只存储一次,而这些项目的多个表示可以使用各种 ID 数组保存。

从那里,您可以通过映射您关心的任何 ID 数组并按其 ID 检索项目来汇总实际项目的列表。

所以,最终的答案是 just byId 对象的键不会给你任何排序,也不允许定义数据的子集。