Redux建议使用规范化的应用程序状态树,但我不确定在这种情况下是否是最佳实践。假设以下情况:
- 每个
Circle
有多个Posts
。 - 每个
Post
有多个Comments
。
在后端数据库中,每个模型如下所示:
Circle:
{
_id: '1'
title: 'BoyBand'
}
职位:
{
_id: '1',
circle_id: '1',
body: "Some Post"
}
评论:
{
_id: '1',
post_id: '1',
body: "Some Comment"
}
在前端应用程序状态(所有reducers的最终结果)中,其外观如下:
{
circles: {
byId: {
1: {
title: 'BoyBand'
}
},
allIds: [1]
},
posts: {
byId: {
1: {
circle_id: '1',
body: 'Some Post'
}
},
allIds: [1]
},
comments: {
byId: {
1: {
post_id: '1',
body: 'Some Comment'
},
allIds: [1]
}
}
现在,当我进入CircleView
页面时,我从后端获取Circle
,其中包含与之相关的所有posts
和comments
。
export const fetchCircle = (title) => (dispatch, getState) => {
dispatch({
type: constants.REQUEST_CIRCLE,
data: { title: title }
})
request
.get(`${API_URL}/circles/${title}`)
.end((err, res) => {
if (err) {
return
}
// When you fetch circle from the API, the API returns:
// {
// circle: circleObj,
// posts: postsArr,
// comments: commentsArr
// }
// so it's easier for the reducers to consume the data
dispatch({
type: constants.RECEIVE_CIRCLE,
data: (normalize(res.body.circle, schema.circle))
})
dispatch({
type: 'RECEIVE_POSTS',
data: (normalize(res.body.posts, schema.arrayOfPosts))
})
dispatch({
type: 'RECEIVE_COMMENTS',
data: (normalize(res.body.comments, schema.arrayOfComments))
})
})
}
到目前为止,我认为我以相当标准的方式完成了所有工作。但是,当我想要渲染每个Post
组件时,我意识到与将帖子与其评论一起填充相比,这种方法变得低效(O(N^2))。保持状态树如下格式可以提高效率。
{
circles: {
byId: {
1: {
title: 'BoyBand'
}
},
allIds: [1]
},
posts: {
byId: {
1: {
circle_id: '1',
body: 'Some Post'
comments: [arrOfComments]
}
},
allIds: [1]
}
}
这与我对redux状态树的理解相悖,我认为在redux状态树中,最好保持所有内容都规范化。
问:实际上,在这种情况下,我应该保持内容非规范化吗?我如何确定该做什么?