问题描述
我在这里发布了一些关于 SWR hook 的问题,因为在我尝试使用它的过程中,我遇到了一些问题,这有点困难
我想要做的是在我的 API 中设置一个断点来尝试获取一些数据(顺便说一下,我正在使用 axios)现在的问题是,我有从 useSWR 中解构 {data}
,因为这是我从 axios 接收的数据,我认为这会导致参数出现问题,我必须将其传递给钩子才能使一切正常。
让我给你看一些代码
使用 useSWR
const Part1 = () => {
const router = useRouter();
const [searchBar,setSearchBar] = useState<boolean>(false);
const [userId,setUserId] = useState<dataObject>({});
const [results,setResults] = useState<string>("");
// Searchbar users
useEffect(() => {
const auth: dataObject = JSON.parse(localStorage.getItem("Auth"));
setUserId(auth);
},[]);
const { data }: multipleUsers = useSWR(
() => "http://localhost:5000/api/user/allU/" + userId.user.id,fetcher,"",data
);
如你所见,我传递给函数的最后一个参数是名称数据,因为如果我不这样做,它会给我错误(如前所述,我已经发布了一个关于该问题的问题),这是
Block-scoped variable 'data' used before its declaration.ts(2448)
Part1.tsx(41,11): 'data' is declared here
目标:那里发生了什么,我该如何解决这个问题?具体是什么原因造成的,为什么?
感谢您的时间!
更新
const { data }: multipleUsers = useSWR<user[]>(
() => "http://localhost:5000/api/user/allU/" + userId.user.id,""
);
Expected 4 arguments,but got 3.ts(2554)
use-swr.d.ts(4,99): An argument for 'Data' was not provided
解决方法
这是 useSWR
函数签名 (source):
function useSWR<Data = any,Error = any>(
...args:
| readonly [Key]
| readonly [Key,Fetcher<Data> | null]
| readonly [Key,SWRConfiguration<Data,Error> | undefined]
| readonly [
Key,Fetcher<Data> | null,Error> | undefined
]
): SWRResponse<Data,Error>
您可以将预期的数据类型作为第一个类型参数传递,如下所示:
const { data } = useSWR<User[]>(
() => "http://localhost:5000/api/user/allU/" + userId.user.id,fetcher
)
还要注意的是,你给函数传递了 4 个参数,但是没有覆盖支持 4 个参数,最大是 3 个,当然可以少一些。
编辑:
再看看 args
类型:
| readonly [Key]
| readonly [Key,Fetcher<Data> | null]
| readonly [Key,Error> | undefined]
| readonly [
Key,Error> | undefined
]
只有一种变体有 3 个参数,就是这个:
readonly [
Key,Error> | undefined
]
看一下第三个参数类型:
SWRConfiguration<Data,Error> | undefined
甚至不检查源代码,它可能是某种对象。你通过了什么?空字符串:""
。
要么删除这个参数,要么传递一个配置对象。