【发布时间】:2018-05-03 14:02:10
【问题描述】:
我正在开发一个天气应用程序,使用 openweathermap API,我已经成功实现了一切,现在我想使用来自 expo 的 Apploading 从 API 获取结果,所以当 mainScreen 打开时,所有数据都被获取并呈现在屏幕上,而不是等待 API 的响应,
weatherAPI.js:
const rootUrl = 'http://api.openweathermap.org/data/2.5/weather?appid=API_KEY'
export const fetchWeather = (lat,lon) => {
const url = rootUrl+'&lat='+lat+"&lon="+lon+"&units=metric"
console.log(url)
return fetch(url)
.then(res => res.json())
.then(json => ({
temp: json.main.temp,
pressure: json.main.pressure,
humidity: json.main.humidity,
maxTemp: json.main.temp_max,
minTemp: json.main.temp_min,
weather: json.weather[0].main,
weatherDescription: json.weather[0].description,
name: json.name,
country: json.sys.country,
windSpeed: json.wind.speed,
windDeg: json.wind.deg,
clouds: json.clouds.all,
sunrise: json.sys.sunrise,
sunset: json.sys.sunset,
}))
}
Home.js:
componentDidMount(){
this._getData()
}
_getData(){
navigator.geolocation.getCurrentPosition(
(posData) => fetchWeather(posData.coords.latitude, posData.coords.longitude)
.then(res => this.setState({
temp: Math.round(res.temp),
weather: res.weather,
weatherDescription: res.weatherDescription,
name: res.name,
country: res.country,
})),
(error)=> alert(error),
{timeout:10000}
)
}
也许这是一个非常基本的问题:
我想创建一个加载图标来重新加载数据?我对这个解决方案的方法是使用 onPress 调用 this_getData() 的 touchableOpacity,但我觉得编码明智吗?
【问题讨论】:
标签: api react-native jsx