在使用以react native编写的Weather应用程序上工作时,在iOS上运行正常时,我在Android上收到``网络请求失败''错误。
这是提取功能-
componentDidMount: function() {
navigator.geolocation.getCurrentPosition(
location => {
// this variable will contain the full url with the new lat and lon
var formattedURL = REQUEST_URL + "lat=" + location.coords.latitude + "&lon=" + location.coords.longitude+"&APPID=e5335c30e733fc682907a126dab045fa";
// this will output the final URL to the Xcode output window
console.log(location.coords.latitude);
console.log(location.coords.longitude);
console.log(formattedURL);
// get the data from the API
this.fetchData(formattedURL);
},
error => {
console.log(error);
});
},
// fetchdata takes the formattedURL, gets the json data and
// sets the apps backgroundColor based on the temperature of
// the location
fetchData: function(url) {
fetch(url)
.then((response) => response.json())
.then((responseData) => {
// set the background colour of the app based on temperature
var bg;
var temp = parseInt(responseData.main.temp);
if(temp < 14) {
bg = BG_COLD;
} else if(temp >= 14 && temp < 25) {
bg = BG_WARM;
} else if(temp >= 25) {
bg = BG_HOT;
}
// update the state with weatherData and a set backgroundColor
this.setState({
weatherData: responseData,
backgroundColor: bg
});
})
.done();
},
我在这里也提到了关于stackoverflow的其他问题,但是它们都围绕着将localhost更改为您的本地IP地址(如127.0.0.1)。就我而言,我没有在哪里使用本地主机。
最佳答案
检查模拟器旁边的Android模拟器选项面板,您将有更多选项,然后转到蜂窝网络并检查数据状态和网络类型。尝试将网络类型更改为“完整”,将数据状态更改为“家庭”。尝试使用各种选项来选择网络类型和数据状态,然后检查其是否正常工作...