我正在尝试使用下面的自定义挂钩,但它没有按预期工作
CustomHook:
import { useEffect, useState } from 'react'
import { createAPIInstance } from '../utils/api'
import { getBaseUrl } from '../utils/functions'
const BASE_URL = getBaseUrl()
const useGetAPI = (endpoint) => {
const [data, setData] = useState([])
const api = createAPIInstance()
const getData = async () => {
const response = await api.get(`${BASE_URL}${endpoint}`)
setData(response.data)
}
useEffect(() => {
getData()
}, [])
return data
}
export {
useGetAPI
}
这是自定义挂钩使用
app.js
function App() {
const [details, setDetails] = useState({})
useEffect(() => {
const fetchData = async () => {
const details = useGetAPI('/some-api-endpoint')
setDetails(details)
}
fetchData()
}, [])
return (
<div></div>
)
}
铬控制台错误:
Uncaught (in promise) Invariant Violation: 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 fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.
at invariant
React版本:16.13.1React Dom版本:16.13.1
对于app.js
:
为什么在同一位置初始化函数?
示例:
const fetchData = async () => {
const details = useGetAPI('/some-api-endpoint')
setDetails(details)
}
useEffect(async () => {
fetchData()
}, [])
你没有export default
你的功能。
示例:
export default function App() {
对于CustomHook
:
您没有说,因为您的函数使用的是async
值。
示例:
const useGetAPI = async (endpoint) => {
useEffect(async () => {