如何解决在SWR上禁用预取
我正在尝试为数据获取实现swr库。我曾经使用普通的axios和我创建的一些自定义钩子。 我遇到的问题是由于某种原因,swr在设置默认axios标头之前触发了get请求,因此在发送标头时缺少了该标头,该标头用于标识我的应用程序的帐户。 我的猜测是它与SWR的预取功能有关,但这只是一个疯狂的猜测,不知道如何防止这种情况的发生。
import axios from "axios";
import React,{useLayoutEffect} from "react";
import useSWR from "swr";
function Child({match}) {
const fetcher = () => {
console.log('Should happen second')
axios.get('https://api.mydomain.com').then(res => res.data)
}
const {data} = useSWR('/account/specific/data',fetcher)
return <div>{JSON.stringify(data)}</div>
}
export default function Account({match}) {
let accountId = match.params.accountId;
useLayoutEffect(() => {
console.log('Should happen first')
axios.defaults.headers.common["Account-Token"] = accountId;
},[accountId]);
return <Child/>
}
解决方法
您正在弄错imo序列。
1)如果尚未准备好生成组件,则应该返回null。
export default function Account({match}) {
let accountId = match.params.accountId;
useLayoutEffect(() => {
console.log('Should happen first')
axios.defaults.headers.common["Account-Token"] = accountId;
},[accountId]);
if (!accountId) return null //<-- don't generate the Child component until you are ready.
return <Child/>
}
2)如果您确实想在挂载时禁用SWR提取,请设置{revalidaOnMount:false}
例如
const {data} = useSWR('/account/specific/data',fetcher,{ revalidateOnMount: false})
3)或您可以使用条件提取,以便仅在变量准备就绪时才进行提取。
const { data } = useSWR( accountID ? /url/path : null,fetcher )
当键为null时,useSWR钩子不会调用提取程序。
,您使用的 axios 没有 async 和 await ,而且您在方法提取器中也没有 return ,请更改此方法下一个方式:
const fetcher = async () => {
return await axios.get('https://api.mydomain.com').then(res => res.data)
}
,
我能够解决将initialData添加到useSWR挂钩上的选项的问题。
const { data,error } = useSWR('/api/data',initialData: [],revalidateOnMount: true)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。