[英]React/Redux Handling Two-Way Data
我正在努力正确地组织我的Redux Store和我的React组件以正确处理双向嵌套数据。
假设我有一个post
模型和一个user
模型。 让我们举一个抽象的例子:
const user = {
"id": "1",
"name": "user 1",
"posts": [...] // list of post objects
}
const post = {
"id": "1",
"title": "post 1",
"user": user
}
问题是我无法像这样加载此数据,因为它将导致无限递归错误。 我必须忽略user
的posts
或忽略user
的posts
。
这是我理想中需要的:
我需要有一个post
页面显示后user
与所有他的信息(ID,姓名)和用户的列表posts
与职位信息(ID,标题)在同一个屏幕上同时。
我使用normalizr
标准化数据。
我将如何加载数据?
根据Redux文档( https://redux.js.org/recipes/structuring-reducers/normalizing-state-shape ),您应该避免嵌套对象。
这里的解决方案是像对待数据库一样对待数据。 这意味着您应该存储ID而不是对象。
在您的示例中:
const user = {
"id": "1",
"name": "user 1",
"posts": ["1", "2", ...] // list of post objects IDs
}
const post = {
"id": "1",
"title": "post 1",
"userId": "1"
}
通常,您只将post_ids
保存在用户中,将user_id
保存在帖子中。 可以将normalizer
模式配置为处理那些关系。
在post
中添加user
密钥的动机是什么? 在两个相关的数据结构中共享数据是多余的。 你应该有唯一的数据post
的相关数据,您需要正确的关联信息的最小量user
与他/她的post
秒。 我想您会希望在post
中使用用户的字符串名称,或者在每个post
对象中使用用户的ID号
const user = {
"id": "1",
"name": "user 1",
"posts": [...] // list of post objects
}
const post = {
"id": "1",
"title": "post 1",
"user": "user 1"
}
编辑:从您的评论,我将使所有users
的数组。 但是, post
键只是与该用户关联的帖子的ids
。 还有另一组只有posts
。 和以前一样,具有将两者关联的标识符。 之后,根据需要解析前端。
const users = [
{ name: 'andrew', id: 10, postIds: [1,3,23,30]},
// ...more users
]
const posts = [
{ name: 'a post', id: 23, userId: 10 }
{ name: 'another post', id: 3, userId: 10 }
{ name: 'a third post', id: 2, userId: 3 }
// ...more posts
]
从技术上讲, userId
是可选的,但在检查单个帖子时能够识别用户可能是一个很好的选择
编辑:哇,我只是向下滚动,看到诺德在我之前有完全一样的提议。 很高兴看到我们在同一页面上,但是,如果您喜欢这个主意,请确保他/她得到好评;)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.