在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?
发布评论
评论(1)
不鼓励突变,不应使用。问题是,虽然看起来可能会在一见钟觉上起作用,因为缓存的值确实会更改,但参考值保持不变,因此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.