我有一个包含posts的redux状态,我将其存储为具有以下形状的单个对象:
posts: {
1: { isPublic: true, content: 'foo' },
2: { isPublic: true, content: 'bar' },
3: { isPublic: false, content: 'foobar' },
}
我使用reselect从我的组件中获取状态,我为此创建了两个选择器:
const getPostsEntities = (state) => state.posts;
export const getPosts = createSelector(
[ getPostsEntities ],
(posts) => Object.keys(posts).map( id => posts[id])
);
export const getPublicPosts= createSelector(
[ getPostsEntities ],
(posts) => Object.keys(posts).map( id => posts[id]).filter( post => post.isPublic )
);
我的怀疑是这部分似乎是多余的任何选择器
(帖子(=>Object.keys(posts(.map(id=>posts[id](
我曾想过让getPostsEntities
直接返回数组,但我在理解什么是最佳做法方面遇到了一些问题
正如@HMR所提到的,您可以在另一个选择器中使用一个重新选择选择器。因此CCD_ 2可以基于来自CCD_ 3的记忆结果。您也可以使用Object.values()
而不是Object.keys()
。
const getPostsEntities = (state: State) => state.posts;
export const getPosts = createSelector(
[ getPostsEntities ],
(posts) => Object.values(posts)
);
export const getPublicPosts = createSelector(
[ getPosts ],
(posts) => posts.filter(post => post.isPublic)
);