How do I create a globally accessible variable in React JS

邮差的信 提交于 2019-12-11 04:13:59

问题


In my react JS app, I make many API calls,

Rather than having to specify: const BASE_URL = 'https://apiurlgoeshere.com/'

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


回答1:


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.

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;

and import this everywhere the axios is going to be used like:

import axios from "./axios-instance";

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.




回答2:


If webpack is being used for code bundle, DefinePlugin can be used.

new webpack.DefinePlugin({
    'BASE_URL': JSON.stringify('https://apiurlgoeshere.com/')
});

For gulp build, gulp-replace can be used.

.pipe(replace('BASE_URL', 'https://apiurlgoeshere.com/'))



来源:https://stackoverflow.com/questions/53651101/how-do-i-create-a-globally-accessible-variable-in-react-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!