我试图使用useSWR在点击按钮。我希望在单击按钮时,使用useSWR的API调用将启动,但我得到错误。错误是这样的:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
这是我的代码:
const onStartPro =() => {
const token = session?.user?.access_token
const url = process.env.BASE_URL + GET_PRO
const {
data: items,
error,
isLoading,
} = useSWR(process.env.BASE_URL + 'pro user', getAuthenticatedClientSide(token,GET_PRO))
}
这是我的get函数:
export const getAuthenticatedClientSide = async (token, endpoint) => {
const url = process.env.BASE_URL + endpoint
try {
const res = await wretch(url).auth(`Bearer ${token}`).get().json()
return res
} catch (e) {
const error = new Error(e)
error.info = e.message
error.status = e.status
throw error
}
}
我哪里错了?请帮帮我:(
2条答案
按热度按时间oaxa6hgo1#
useSwr是一个钩子函数,它和useEffect一样。所以你不能在事件函数内部使用。你应该尝试axios或fetch,就像你的event fun中的普通函数ccall一样。
使用提取器函数
zzlelutf2#
如果你想在这个方法中调用一个SWR,你必须在
useEffect
中使用它如果你只想调用一次,你必须像这样传递一个变量给useEffect
: