突变使用WRR数据(本地状态)而不重新验证?
我有一些我使用useswr futce的数据,现在我想对此进行操作。以前,我会在API的响应中setState
,然后在其上操作时,我只需用setState
覆盖它。
就我而言,我想用按钮按按钮对数据进行排序。看起来像这样,
function Component() {
const { data } = useSWR(...)
function sortData() {
data.sort(...)
}
}
如何修改data
,而无需使用wrr重新验证并获取新数据?严格来说,这是客户端的需求,API不必担心此分类。
谢谢!
I have some data from a public API that I fetched using useSWR, now I want to operate on that. Previously, I would setState
with the response from an API and then when operating on it I would just overwrite it with setState
.
In my case, I want to sort the data with a button press. it looks like this
function Component() {
const { data } = useSWR(...)
function sortData() {
data.sort(...)
}
}
How can I modify data
like this without having useSWR revalidate and fetch new data? This is strictly a client-side need, the API does not need to worry about this sorting.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 swr v2.0.4 ,实现此目的的签名是
突变(键,回调,选项)
请参阅文档: https://swr.vercel.app/ docs/stumation.en-us#参数
回调
:类似于React的usestate
hook> hooksetState
setState callback IE(prevdata) => newdata
选项
:options.revalidate
tofalse
跳过重新验证或获取数据(在下面的示例中)。我相信您也可以直接从
使用
使用返回(但我不确定API)。大概Using swr v2.0.4, the signature to achieve this is
mutate(key, callback, options)
See the docs: https://swr.vercel.app/docs/mutation.en-US#parameters
callback
: similar to react'suseState
hooksetState
callback i.e(prevData) => newData
options
:options.revalidate
tofalse
skips revalidating or fetching data (in the example below).I believe you can also use
mutate
directly fromuseSWR
return (but I am unsure of the API). Probably这很难说,因为您不是说是什么原因导致SWR重新验证,而是我知道的主要解决方案:
如果您想避免由排序引起的重新提取,但是您将钩子移至父部件中仍然希望正常获取;
将null/a函数作为缓存键: https://swr.vercel.app/文档/有条件提取如果您只想在某些受控条件下获取;
uses uses useswrimmutable: https://swr.vercel.app/docs/docs/docs/revalidation 您根本不想重新提取。
It's hard to say because you're not saying what causes SWR to revalidate but here are the main solutions I know of :
move the hook to the parent component if you want to avoid the re-fetch caused by the sort but you still want to fetch normally otherwise ;
pass null / a function as cache key : https://swr.vercel.app/docs/conditional-fetching if you want to only fetch in certain controlled conditions ;
use useSWRImmutable : https://swr.vercel.app/docs/revalidation if you don't want to re-fetch at all.