【问题标题】:react-native apploading fetchAPI?react-native apploading fetch API?
【发布时间】: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


    【解决方案1】:

    请使用 this 绑定 _getData 或使用粗箭头函数。这可能会解决问题。

    【讨论】:

      【解决方案2】:

      来自 Expo 的 Apploading https://docs.expo.io/versions/latest/sdk/app-loading 的文档,它旨在用于应用程序的初始加载。 一般来说,对于请求天气信息等异步请求,通常有 3 种状态,进度、成功、失败。您应该确保为所有这些状态正确渲染。当获取正在进行时,您可以呈现活动指示器https://facebook.github.io/react-native/docs/activityindicator.html 您可以使用手动重试/更新按钮来获取最新数据,也可以使用计时器以特定时间间隔获取最新数据

      【讨论】:

      • 感谢您的回复,按钮方法:如何重试/更新?我是 react-native 的小菜鸟
      • <Button onClick={this.getData} /> 。您可能想了解箭头函数并将 _getData 更改为 _getData = () => {} 语法
      猜你喜欢
      • 1970-01-01
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 2018-05-21
      • 2021-11-04
      • 2021-06-05
      • 2018-09-19
      • 1970-01-01
      相关资源
      最近更新 更多