问题描述
在我的react JS应用中,我进行了许多API调用,
In my react JS app, I make many API calls,
无需指定:const BASE_URL =' https://apiurlgoeshere.com/'
Rather than having to specify:const BASE_URL = 'https://apiurlgoeshere.com/'
在每个页面上,我都希望在整个应用程序中都可以访问BASE_URL,所以我可以只执行BASE_URL + API_CALL
on every page, I'd rather have BASE_URL accessible throughout the entire application, so I can just do BASE_URL + API_CALL for example
推荐答案
如果这只是添加 BASE_URL
,则可以通过在 constants.js
文件并从那里导出.但是,这使我们每次发出网络请求时都执行 BASE_URL +"something"
,这也不是很理想.另外,在某些情况下,可能还必须共享其他配置,例如必须将通用标头添加到所有请求中.
If this is just adding BASE_URL
, then this can be achieved by declaring it inside a constants.js
file and exporting it from there. But then, that makes us do BASE_URL + "something"
each time we make a network request which isn't really ideal either. Also there might be some scenarios where other configuration have to be shared, like say, a common header that has to be added to all the requests.
为解决此问题,大多数请求库都具有内置解决方案.如果我们选择 axios 作为最受欢迎的浏览器,则可以创建实例,例如:
To solve this, most request libraries have in-build solutions. If we are choosing axios as the most popular one, we can create a instance like:
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
export default instance;
并将其导入到 axios
的任何地方,例如:
and import this everywhere the axios
is going to be used like:
import axios from "./axios-instance";
假设 axios-instance.js
是创建实例的文件.现在,您可以跳过将 BASE_URL
添加到实例中已提供的每个请求中.
assuming axios-instance.js
is the file where the instance is created. Now you can skip adding the BASE_URL
to every request as it is already provided in the instance.
这篇关于如何在React JS中创建全局可访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!