Reactjs Redux:规范化全局状态
假设以下情况:Reactjs Redux:规范化全局状态,reactjs,redux,Reactjs,Redux,假设以下情况: 1. Page has many posts 2. Post has many comments 我有以下减速器: 1. PagesReducer 2. PostsReducer 3. PostReducer 4. CommentsReducer 我现在的状态如下: pagesByTitle: { dorrisPage: { isFetching: false, data: { _id: "..." title: "dorrisPa
1. Page has many posts
2. Post has many comments
我有以下减速器:
1. PagesReducer
2. PostsReducer
3. PostReducer
4. CommentsReducer
我现在的状态如下:
pagesByTitle: {
dorrisPage: {
isFetching: false,
data: {
_id: "..."
title: "dorrisPage",
},
posts: [
{
isFetching: false,
data: {
_id: "..",
body: ".."
},
comments: [..]
}
]
}
}
上面的结构最初看起来不错,但我意识到我必须为子状态传递操作。例如,如果我发送了一个名为
ADD_COMMENT
我将把操作传递到PagesReducer
、PostsReducer
、PostsReducer
和CommentsReducer
,最后CommentsReducer
将处理该操作。我想这就是我意识到为什么在Redux中建议规范化状态的时候了
你能帮我回答以下问题吗
在这种情况下,我规范化状态的动机正确吗
规范化示例状态的最佳方法是什么
应避免嵌套
引用redux文档:
在一个更复杂的应用程序中,您需要不同的实体
相互参照。我们建议你保持你的状态
尽可能规范化,无任何嵌套。将每个实体保持在一个
对象,并使用ID从中引用它
其他实体或列表。把应用程序的状态想象成一个数据库。这
normalizer的文档中详细描述了该方法
对于规范化状态,可以使用
订购物品时需要“ItemId”
那么减速机可能是这样的
export const posts = (state = initialState, action) => {
switch (action.type) {
case type.FETCH_POSTS_REQUEST:
case type.FETCH_POSTS_FAILURE:
return {...state, isFetching: action.isFetching};
case type.FETCH_POSTS_SUCCESS:
return {...state,
isFetching: action.isFetching,
items: action.entities.posts, itemsIds: action.result
};
case type.DELETE_POST:
return {...state,
items: omit(state.items, action.id),
itemsIds: state.itemsIds.filter(id=>id !== action.id)
};
case type.UPDATE_POST:
return {...state, items: {...state.items,
[action.post.id]: {...state.items[action.post.id],...action.post}}};
default:
return state;
}
}
通过id更容易查询帖子:
const mapStateToProps = (state,ownProps) =({
post:state.posts.items[ownProps.id]
})
对于从redux store计算派生数据,您可以使用创建可记忆的、可组合的选择器函数
const mapStateToProps = (state,ownProps) =({
post:state.posts.items[ownProps.id]
})