簡體   English   中英

React Native-在API中顯示來自API的數據<Text>

[英]React Native - show data from an API in a <Text>

我正在使用fetch()從外部數據獲取數據,並希望將其顯示在View

console.log(responseJson)從API顯示數據,但是<Text> this.state.data沒有顯示。

我的應用程序中顯示的全部是“ Temperatur:C”。

運行時沒有出現任何錯誤。

我的this.state.data不是顯示它的正確方法嗎?

import React, { Component } from 'react'
import { StyleSheet, Text, View, Image, Button, Alert } from 'react-native';


class Wether extends Component {
    state = {
       data: ''
    }
    componentDidMount = () => {
       fetch('https://opendata-download-metfcst.smhi.se/api/category/pmp2g/version/2/geotype/point/lon/16/lat/58/data.json',{
          method: 'GET'
       })
       .then((response) => response.json())
       .then((responseJson) => {
          console.log(responseJson);

          this.setState({
             data: responseJson
          })
       })
       .catch((error) => {
          console.error(error);
       });
    }
    render() {
       return (
          <View>
             <Text>
                Temperatur: {this.state.data} C
             </Text>
          </View>
       )
    }
 }
 export default Wether

我的console.log(responseJson)顯示:

Object {
       "parameters": Array [
         Object {
           "level": 0,
           "levelType": "hmsl",
           "name": "msl",
           "unit": "hPa",
           "values": Array [
             1005,
           ],
         },

當我檢查了您的代碼后,似乎一切都很好。 您應該考慮的一件事就是您的響應JSON數據對象。

您不應將您的Response JSON數據顯示在文本組件中

<View style={{flex:1, alignItems:'center', justifyContent:'center'}}>
  <Text>
   Temperatur: { this.state.data.approvedTime } C
  </Text>
</View>

請再次重新檢查您的代碼,希望對您有所幫助。

您應該在構造函數中初始化狀態 ,並且可以在其他任何地方使用this.setState()

import React, { Component } from 'react'
import { StyleSheet, Text, View, Image, Button, Alert } from 'react-native';


class Wether extends Component {
    constructor(props) {
        super(props);
        state = {
           data: ''
        }
    }
    componentDidMount = () => {
       fetch('https://opendata-download-metfcst.smhi.se/api/category/pmp2g/version/2/geotype/point/lon/16/lat/58/data.json',{
          method: 'GET'
       })
       .then((response) => response.json())
       .then((responseJson) => {
          console.log(responseJson);

          this.setState({
             data: responseJson
          })
       })
       .catch((error) => {
          console.error(error);
       });
    }
    render() {
       return (
          <View>
             <Text>
                Temperatur: {this.state.data} C
             </Text>
          </View>
       )
    }
 }
 export default Wether

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM