如何检查获取是否通过,如果是,显示它?反应本机

How to check if fetch is coming through and if so, display it? React Native

我正在尝试使用 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, Text, 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 端点是否 returns 状态代码在 200-299 范围内。

FetchWeather() 正在返回一个承诺,因此您需要访问该承诺的值。这可以像这样完成:

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

Fetch response.ok

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

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

我已经在 CodeSandbox 上测试过了,你可以看看工作原型。