繁体   English   中英

如何检查 fetch 是否通过,如果是,则显示它? 反应原生

[英]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',
  },
});

这是天气 function:

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;

这是实际获取的 function:

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;

这个 function 是否有效并实际收到 json? 有没有办法查看它是否正在获取? 如果这是有效的,为什么不显示温度?

非常感谢。

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

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

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

获取响应.ok

如何访问 promise 的值。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM