在setquerydata中突变以前的数据

发布于 2025-01-25 13:01:22 字数 1336 浏览 1 评论 0 原文

在React-Query中, setquerydata 在此功能中,哪个接受更新功能

setQueryData('myQuery', oldData => newData);

可以突变旧数据并将其返回? 例如

setQueryData('myQuery', oldData => {
    oldData.foo = 42;
    return oldData
}

,或者是OldData 不可变的,必须使用REST/差异操作员或EG incrimer 进行修改?

示例 全部显示返回新实例,但文档并未明确说出一种或另一种方式。

到位似乎有效,但我不确定是否有任何陷阱。我知道eg setstate 我必须返回一个新值。

为什么不返回新实例,以防万一?查询数据很大,我只需要修改一个字段。

更新

查看 query :: setData setQueryData 调用的内容,据我所知,在所有情况下,在 setQueryDataa的所有情况下,都会通过调用 dispatch 来通知查询的观察者。 被调用;当 OldData newdata 等于时,我看不到早期。鉴于此,是否有风险?

In react-query, setQueryData has an overload which accepts an update function as such

setQueryData('myQuery', oldData => newData);

In this function is it ok to mutate the state of oldData and return it?
For example

setQueryData('myQuery', oldData => {
    oldData.foo = 42;
    return oldData
}

Or is oldData immutable and must be modified with rest/spread operators or e.g. immer?

The examples all show returning a new instance, but documentation does not explicitly say one way or the other.

Mutating in place seems to work but I'm not sure if there are any pitfalls. I know with e.g. setState I would have to return a new value.

Why not return a new instance just in case? The query data is very big and I only need to modify a single field.

Update

Looking at the source code of query::setData which is what setQueryData calls, as far as I can tell the observers of the query will be notified via a call to dispatch in all cases where setQueryData is called; I don't see an early-out when oldData is reference-equal to newData. Given this, are there any risks?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

百思不得你姐 2025-02-01 13:01:22

不鼓励突变,不应使用。问题是,虽然看起来可能会在一见钟觉上起作用,因为缓存的值确实会更改,但参考值保持不变,因此React-Query will not> not 将更改告知观察者。

与React中的大多数数据结构一样,最好不成功。

mutating is discouraged and should not be used. The problem is that while it looks like it might work on first sight because the cached value does get changed, the reference stays the same, so react-query will not inform observers of the change.

As with most data structures in react, it is better to work immutably.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文