如何检查是否正在获取数据,如果显示,则显示它?反应本机

问题描述

我正在尝试使用React Native来编码应用程序。我目前正在开发天气应用。我使用的数据应该从OpenWeather中获取。问题是温度未在应用程序上显示。我正在使用Expo来测试应用程序。

这是显示代码:

import React from 'react';
import { StyleSheet,Text,View } from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';  // Background color
import { Key } from './Key';

import Weather from './components/Weather';

export default class App extends React.Component {
  state = {
    isLoading: false
  };

  render() {
    const { isLoading } = this.state;
    return (
      <View style={styles.container}>
        {isLoading ? (
          <Text>Please wait a moment...</Text>   // PROBLEM: THIS IS NOT CENTERED!!!!!!!!
        )
          : (
            <View style={styles.container}>
              {/*Following JSX adds the background gradient color. Inside will contain all the information for the app*/}
              <LinearGradient
                // Background Linear Gradient
                colors={['#3d94ee','#123161']}
                style={{ flex: 1 }}
              >
                <Weather />

              </LinearGradient>
            </View>
          )
        }
      </View>
    );
  }
}


const styles = StyleSheet.create({
  container: {
    flex: 1,flexDirection: 'column',justifyContent: 'center',},});

这是天气功能:

import React from 'react';
import { View,StyleSheet } from 'react-native';
import { MaterialCommunityIcons } from '@expo/vector-icons'; // Weather icons
import { FetchWeather } from './fetchWeather'
// This component adds the city,weather description,weather icon,and temperature

const Weather = () => {
  return (
    <View style={styles.container}>
      <Text style={styles.location}>Minneapolis</Text>
      <Text style={styles.weatherDescription}>Clear/Sunny</Text>
      <MaterialCommunityIcons name="weather-sunny" style={styles.weatherIcon} />
      <Text style={styles.temperature}>{FetchWeather}</Text>
    </View>
  );
};

(Stylesheet hidden)

export default Weather;

这是实际的提取功能:

const FetchWeather = () => {
  var key = 'de2570a4ab61d3ede83290dec6fa1725';
  return fetch('api.openweathermap.org/data/2.5/weather?id=5037649&appid=' + key)
  .then((response) => response.json())
  .then((json) => {
    return json.main.temp;
  })
};

export default FetchWeather;

此函数有效并且实际上接收到json吗?有没有办法查看它是否正在获取?如果有效,为什么不显示温度?

非常感谢。

解决方法

要检查获取是否成功,可以检查response.ok的值以查看API端点是否返回200-299范围内的状态代码。

FetchWeather()返回了承诺,因此您需要访问承诺的值。可以这样完成:

let temp = await FetchWeather();
//temp = 298.08

Fetch response.ok

How to access the value of a promise.

,

该功能有效,并且也有效。您只需要一种更好的方式来处理响应。 您可以使用状态来存储数据,并使用它来在Weather函数中呈现值。

FetchWeather().then((data) => {
   // setState(data);
});

我已经在CodeSandbox上对其进行了测试,您可以看一下工作的原型。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...