首页 > 解决方案 > 在本机反应中显示一个json对象

问题描述

我正在创建一个显示从 json api 获取的信息的应用程序。

我能够获取 json 并使用 console.log 将其打印到控制台。

我希望能够将部分 json 打印到应用程序中,例如位置。

这是我尝试过的代码

export default class App extends React.Component {
constructor (props) {
  super(props);
  this.state = {
    loading: true,
    dataSource: []
  };
}
componentDidMount() {
const fetch = require('node-fetch');
 fetch('https://api.weatherapi.com/v1/forecast.json', {
   method: 'GET',
   headers: {
    'Content-Type': 'application/json'
   },
 }).then((response) => response.json())
   .then((responseJson) => {
   console.log(responseJson);
  
     this.setState({
       loading: false, 
       dataSource: responseJson,
       
     })
     console.log(responseJson);
   }).catch((error) => {
     console.error(error);
   });
}



FlatViewItemSeparator = () => {
  return (
    <View
    style={{
      height: .5,
      width: "100%",
      backgroundColor: "#000",
    }}
  />
  );
}


  render(){
    if (this.state.loading) {
  return (
    <View style={{flex: 1, paddingTop: 20}}>
     <ActivityIndicator /> 
  
  </View>
  );
    }
return (
    <View style={{flex: 1}}>
    <FlatList
    
     data={this.state.dataSource}

     ItemSeparatorComponent = {this.FlatListItemSeparator}

     renderItem={({item}) => 
     
     <View style={{flex:1}}>
       <Text>{item.location.name}</Text>
     </View>
     }
         
     keyExtractor={(item, index) => index.toString()}

  />
  </View>
)
  }
}

这是一些json

{
    "location": {
        "name": "New York",
        "region": "New York",
        "country": "United States of America",
        "lat": 40.71,
        "lon": -74.01,
        "tz_id": "America/New_York",
        "localtime_epoch": 1623330602,
        "localtime": "2021-06-10 9:10"
    },
    "current": {
        "last_updated_epoch": 1623326400,
        "last_updated": "2021-06-10 08:00",
        "temp_c": 24.4,
        "temp_f": 75.9,
        "is_day": 1,
        "condition": {
            "text": "Partly cloudy",
            "icon": "//cdn.weatherapi.com/weather/64x64/day/116.png",
            "code": 1003
        },
        "wind_mph": 5.6,
        "wind_kph": 9.0,
        "wind_degree": 70,
        "wind_dir": "ENE",
        "pressure_mb": 1017.0,
        "pressure_in": 30.5,
        "precip_mm": 0.0,
        "precip_in": 0.0,
        "humidity": 54,
        "cloud": 75,
        "feelslike_c": 25.5,
        "feelslike_f": 77.8,
        "vis_km": 16.0,
        "vis_miles": 9.0,
        "uv": 6.0,
        "gust_mph": 12.3,
        "gust_kph": 19.8
    }
   }

当我运行应用程序时,出现以下错误

错误:应用程序(...):渲染没有返回任何内容。这通常意味着缺少 return 语句。或者,不渲染任何内容,返回 null。

标签: javascriptjsonreact-native

解决方案


import React from "react";
import {
  ScrollView,
  StyleSheet,
  Text,
  View,
  TextInput,
  TouchableOpacity,
  FlatList,
  ActivityIndicator
} from "react-native";
export default class App extends React.Component {
constructor (props) {
  super(props);
  this.state = {
    loading: true,
    dataSource: [],
  };
}
componentDidMount() {
  //this.setState({loading:true});
  const fetch = require('node-fetch');
 fetch('https://api.weatherapi.com/v1/forecast.json', {
   method: 'GET',
   headers: {
    'Content-Type': 'application/json'
   },
 }).then((response) => response.json())
   .then((responseJson) => {
   console.log(responseJson);
  
     this.setState({
       loading: false, 
       dataSource: responseJson,
       
     })
     console.log(responseJson);
   }).catch((error) => {
     console.error(error);
   });
}



FlatViewItemSeparator = () => {
  return (
    <View
    style={{
      height: .5,
      width: "100%",
      backgroundColor: "#000",
    }}
  />
  );
}


  render(){
  return (
    <View style={{flex:1}}>
      {
        this.state.loading ==true?
        <View style={{paddingTop: 20}}>
          <Text>Hello</Text>
         <ActivityIndicator color='#000'/> 
      
      </View>
      :
     
        <View >
           {

             this.state.dataSource.error.code==1002?
             <View>
               {/* <ActivityIndicator color='#000'/>  */}
             <Text>
             { this.state.dataSource.error.message}
            </Text>
            </View>
            :
        <FlatList
        
         data={this.state.dataSource}
    
         ItemSeparatorComponent = {this.FlatListItemSeparator}
    
         renderItem={({item}) => 
         
         <View style={{flex:1}}>
          
            <Text>{item.location.name}</Text>
          
           
         </View>
         }
             
         keyExtractor={(item, index) => index.toString()}
    
      />
        }
      </View>
      }

    </View>

  )
  }
}

在此处输入图像描述


推荐阅读