reactjs - 我将如何规范这个嵌套的减速器案例?
问题描述
我将如何规范这个嵌套的减速器案例?
这段代码工作正常,但我想像 redux 文档推荐的那样对其进行规范化。
case POST_COMMENT_SUCCESS:
// adds a comment to a post without having to re render.
// console.log(action.data.commentBody);
return {
...state,
images: state.images.map((image) => {
// appends new comment withing images redux state. only if image.id === action.id
if (image.id === action.id) {
return {
...image,
comments: [
...image.comments,
{
comment_body: action.data[0].comment_body,
user: {
username: action.data[0].user.username,
},
},
],
};
}
return image;
}),
};
控制台日志
console.log(action.data) //
数据结构
{
"id": 55,
"comment_body": "ddadada",
"created_at": "2019-07-24T19:02:38.805Z",
"updated_at": "2019-07-24T19:02:38.805Z",
"user_id": 1,
"image_id": 168,
"user": {
"id": 1,
"googleId": null,
"username": "*****od",
"password": "$2b$12$Al888888********O",
"email": "e*********",
"created_at": "2019-06-23T18:57:17.253Z",
"updated_at": "2019-06-23T18:57:17.253Z"
}
}
有没有办法可以使用插件进行 redux 规范化,或者在这个 reducer 案例中我可以改变一些东西来规范化它?
解决方案
您可能希望从图像中分离出评论并使用外键将两者关联起来。虽然它现在可以工作,但当该数组开始增长到 1000 等大小时,它会失去规模,因为找到特定图像的唯一方法是遍历数组。
如果您使用键为 id 的对象,则无需遍历数组并直接查找和引用数据
// images store
images: {
byId: {
168: {
commentsById: [55]
}
}
}
// comments store
comments: {
byId: {
55: {
"id": 55,
"comment_body": "ddadada",
"created_at": "2019-07-24T19:02:38.805Z",
"updated_at": "2019-07-24T19:02:38.805Z",
"user_id": 1,
"image_id": 168,
}
}
}
除了 id 之外,还不需要在此处存储用户数据,因为很难保持这些数据的新鲜,您需要单独存储所有用户
推荐阅读
- wordpress - 什么是美瞳?
- javascript - 如何使用卡片触发点击事件?
- angular - 使用 compodoc 的 Angular 项目文档
- jquery - 如何限制从 MVC 中的模型填充的数据?
- azure-keyvault - 可访问多个密钥保管库的 Azure Web 应用
- javascript - 无法在我的组件中调用 redux 操作
- perl - 为什么这个 Perl foreach 循环只执行一次?
- python - 在 Python2 中编写二进制访问流数据以在 Fortran 中读取
- angular - 错误:Angular 2 中的 BehaviorSubject
- ios - 根据日期对数组进行排序/过滤到字典