gpt4 book ai didi

javascript - 非规范化数据如何导致 React Redux 出现问题?

转载 作者:行者123 更新时间:2023-11-30 00:04:28 25 4
gpt4 key购买 nike

查看 reddit 文档 example来自 redux,Dan 说:

{
selectedSubreddit: 'frontend',
postsBySubreddit: {
frontend: {
isFetching: true,
didInvalidate: false,
items: []
},
reactjs: {
isFetching: false,
didInvalidate: false,
lastUpdated: 1439478405547,
items: [
{
id: 42,
title: 'Confusion about Flux and Relay'
},
{
id: 500,
title: 'Creating a Simple Application Using React JS and Flux Architecture'
}
]
}
}
}

In this example, we store the received items together with thepagination information. However, this approach won’t work well if youhave nested entities referencing each other, or if you let the useredit items. Imagine the user wants to edit a fetched post, but thispost is duplicated in several places in the state tree. This would bereally painful to implement.

谁能解释一下他指的分页信息是什么?另外,如果用户想要编辑获取的帖子会是什么样子?这如何导致帖子在状态树中的多个位置重复?

最佳答案

我相信 lastUpdated 属性是他指的分页数据;它可用于(取决于 API)提取自上次更新以来所做的更改。

您对规范化的困惑是可以理解的,因为他没有提供非规范化方法不好的案例示例 - 尽管在文档的下一段中,他确实提供了规范化方法的示例结构看起来像在需要它的情况下。

但请考虑这种情况:我们仍在管理一个跟踪“帖子”的数据集,这些“帖子”是“subreddits”的一部分。但是现在我们允许单个帖子被“交叉发布”的可能性,并且我们将其表示为包含在交叉发布的每个 subreddit 对象中的同一个帖子。

假设帖子 42 是交叉发布的。现在非标准化状态看起来像这样:

{
selectedSubreddit: 'frontend',
postsBySubreddit: {
frontend: {
isFetching: true,
didInvalidate: false,
items: [ {
id: 42,
title: 'Confusion about Flux and Relay'
}
]
},
reactjs: {
isFetching: false,
didInvalidate: false,
lastUpdated: 1439478405547,
items: [
{
id: 42,
title: 'Confusion about Flux and Relay'
},
{
id: 500,
title: 'Creating a Simple Application Using React JS and Flux Architecture'
}
]
}
}
}

现在用户正在查看 subreddit 'reactjs' 并想要编辑帖子 42 的标题。我们还应该更新 subreddit 'frontend' 下的 SAME 帖子的标题,但是如果没有全面搜索我们的状态,我们无法知道这一点。因此,我们要么进行代价高昂的搜索,要么引入数据完整性问题。

规范化后,这个状态看起来像:

{
selectedSubreddit: 'frontend',
posts: {
42: {
id: 42,
title: 'Confusion about Flux and Relay'
},
500: {
id: 500,
title: 'Creating a Simple Application Using React JS and Flux Architecture'
}
},
postsBySubreddit: {
frontend: {
isFetching: true,
didInvalidate: false,
items: [42]
},
reactjs: {
isFetching: false,
didInvalidate: false,
lastUpdated: 1439478405547,
items: [42,500]
}
}
}

以这种方式存储,帖子 42 的详细信息仅存在于一个地方,因此可以在一个地方对其进行编辑并应用于可能存在的每个引用。

当然,也可以使用对象引用来完成此操作,将相同的对象放入两个子版 block 的数组中。但是,这与 Redux 不是特别兼容,在 Redux 中,状态更改返回新对象而不是改变现有对象。使用规范化引用可以很好地处理不可变数据,这是 Redux 状态的一个优势。

关于javascript - 非规范化数据如何导致 React Redux 出现问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39049885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com