[英]React, getting Invalid Hook Call inside my service for creating an axios instance
I have a simple service.js
that looks like this:我有一个简单的
service.js
,如下所示:
import axios from 'axios'
import { useContext } from 'react'
import APIContext from '../context/api/context'
function GetApi() {
const { API } = useContext(APIContext)
console.log(API)
return API
}
const api = axios.create({
baseURL: `${GetApi()}`,
})
export default api
Whenever I try to use the API, it throws me an error saying:每当我尝试使用 API 时,它都会向我抛出一个错误:
Invalid Hook Call. Hooks can only be called inside the body of a function component
You can call a hook, useContext
in your case, only in a React component or a custom hook (see Rules of Hooks ).您只能在 React 组件或自定义钩子中调用钩子
useContext
(请参阅钩子规则)。
What you can do is to transform your service to a hook:你可以做的就是把你的服务变成一个钩子:
import axios from 'axios'
import { useContext } from 'react'
import APIContext from '../context/api/context'
function useGetApi() {
const { API } = useContext(APIContext)
console.log(API)
const api = axios.create({
baseURL: API,
})
return api;
}
export default useGetApi;
And you use it inside a component or another hook like this:然后你在一个组件或另一个钩子中使用它,如下所示:
const api = useGetApi();
The thing you show is function and not a functional component, where a hook should live.你展示的东西是函数而不是函数组件,钩子应该存在于其中。 You must place hooks in the body of functional components, pass states as props and setters as callbacks if you want to use them if child components.
如果要在子组件中使用它们,则必须将钩子放在功能组件的主体中,将状态作为道具传递,将设置器作为回调传递。
What does APIContext
contain? APIContext
包含什么? Function component
means that you must return jsx, technically a react node. Function component
意味着你必须返回 jsx,技术上是一个反应节点。 So in your case GetApi
is not a react component but a plain funciton.所以在你的情况下
GetApi
不是一个反应组件,而是一个普通的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.