在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])
,我不知道为什么要使用这个模式来工作。我会在容器组件中使用类似import { map } from 'lodash'; someList && map(someList, item => {...})
的东西,只需传递实体mapStateToProps
。
那么,有人可以解释它的目的吗?谢谢。
答案 0 :(得分:2)
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检索项目来汇总实际项目的列表。
所以,最终的答案是,在byId
对象的键上依赖只并不能为您提供任何类型的排序,并且不允许定义数据的子集。