[英]React-Native dynamically change fetch url
I have a Mobile App that either uses a cloud server or a local server to serve information. 我有一个使用云服务器或本地服务器来提供信息的移动应用程序。
In my App.js I have: 在我的App.js中,我有:
helperUtil.apiURL().then((url) => {
global.API_URL = url;
})
The function does something like: 该函数的作用类似于:
export async function apiURL() {
try {
var local = await AsyncStorage.getItem('local')
local = (local === 'true')
if(typeof local == 'undefined') return "https://api.website.com";
else if(!local) return "http://192.168.0.6:8080";
else return "https://api.website.com";
}
catch(err) {
return "https://api.website.com";
}
}
Then my fetch command would be: 然后我的提取命令将是:
fetch(global.API_URL+'/page', {
method: 'GET',
headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer '+this.state.authtoken },
})
I'm running into problems here where the API_URL ends up undefined so I feel like there might be a better solution to this. 我在这里遇到的问题是API_URL最终未定义,所以我觉得可能有一个更好的解决方案。
Open to any and all suggestions. 公开接受所有建议。 Thank you.
谢谢。
Insted of seetting url in global obj always use method which return a Promise, and it will return your global object if exist and if not get data from apiURL function. 插入全局obj中的URL的指示总是使用返回Promise的方法,如果存在则返回全局对象,如果不从apiURL函数获取数据,它将返回全局对象。 With async/await syntax fetch will be executed only when getAPI promise will be resolved and there will be no situation that url is empty.
使用async / await语法,只有在解析getAPI promise且URL不会为空的情况下,才会执行提取。
const getAPI = () => {
return new Promise((resolve, reject) =>{
if(global.API_URL) {
resolve(global.API_URL)
} else {
helperUtil.apiURL().then((url) => {
global.API_URL = url;
resolve(url)
})
}
});
const fetchFunc = async () => {
const url = await getAPI()
fetch(url+'/page', {
method: 'GET',
headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer
'+this.state.authtoken },
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.