Vercel SWR更新路线更改数据
我有使用Vercel SWR加载的分数列表。在我的设置中,IM使用相同的组件渲染分数,但根据用户路由,分数应更新。
路由:
/scores
/SCORES/SOCCER
/scores/basketball
scores.tsx
export function Scores() {
const address = `api/scores`
const fetcher = async (url: string) => {
const response = await axios.get(
url,
)
return response.data
}
const { data, mutate } = useSWR(address, fetcher, {
fallbackData,
revalidateOnFocus: true,
revalidateOnReconnect: true,
refreshInterval: 300000,
shouldRetryOnError: false,
revalidateOnMount: true,
})
return <div>{data.map((score) => <ScoreComponent score={score} />}</div>
}
问题
当页面加载所有内容时,所有内容都按预期工作。当我单击下一个/链接以更改路由时,我可以看到路由器更改,但是数据不会更改。我尝试使用Window.Location更改路线,并且数据按预期更改。
我在听路由器路径变化时尝试使用突变,但这无效。
useEffect(() => {
mutate()
}, [router.asPath])
任何人都知道更改路由时重新加载SWR数据的正确方法吗?
I have a list of scores that I am loading using vercel SWR. In my setup im using the same component to render scores but depending on the users route the scores should be updated.
Routing:
/scores
/scores/soccer
/scores/basketball
Scores.tsx
export function Scores() {
const address = `api/scores`
const fetcher = async (url: string) => {
const response = await axios.get(
url,
)
return response.data
}
const { data, mutate } = useSWR(address, fetcher, {
fallbackData,
revalidateOnFocus: true,
revalidateOnReconnect: true,
refreshInterval: 300000,
shouldRetryOnError: false,
revalidateOnMount: true,
})
return <div>{data.map((score) => <ScoreComponent score={score} />}</div>
}
Problem
When the page loads everything works as expected. When I click on a next/link to change the route I can see the router change but the data doesnt change. I tried using window.location to change the route and the data changes as expected.
I tried using mutate while listening to the router path change but that didnt work.
useEffect(() => {
mutate()
}, [router.asPath])
Anybody know the correct way to reload SWR data when changing routes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果有键更改或通过
突变
函数,SWR将获取数据。根据您的情况,我认为有两种可能的方法:SWR will fetch the data if there is key change or via
mutate
function. Depending on your case, I think there are two possible approach: