React Native显示简单的Json数据

时间:2018-06-29 18:03:55

标签: json reactjs native

我正在尝试创建一个简单的页面,在其中我要显示从Json文件获取的数据。不幸的是,我得到“ Invariant Violation:对象作为React子对象无效(找到:带有键{ts,trend,baro,temp,hum,wind,rain,et,天气预报,sun}的对象)。要呈现子级集合,请改用数组。”

因此它加载了Json,但我无法显示数据。如果尝试了各种方法,但无法解决。

App.js

import React from 'react'
import { AppRegistry, StyleSheet, FlatList, Text, View, Alert, ActivityIndicator, Platform} from 'react-native'

export default class Planner extends React.Component {
  constructor(props)
  {

    super(props);

    this.state = { 
    isLoading: true
  }
  }

  componentDidMount() {

       return fetch('url')
         .then((response) => response.json())
         .then((responseJson) => {
           this.setState({
             isLoading: false,
             dataSource: responseJson
           }, function() {
             // In this block you can do something with new state.
           });
         })
         .catch((error) => {
           console.error(error);
         });
     }

FlatListItemSeparator = () => {
    return (
      <View
        style={{
          height: 1,
          width: "100%",
          backgroundColor: "#607D8B",
        }}
      />
    );
  }

  render() {

    if (this.state.isLoading) {
      return (
        <View style={{flex: 1, paddingTop: 20}}>
          <ActivityIndicator />
        </View>
      );
    }

    return (

<View>

        data ={ this.state.dataSource }

          renderItem={({item}) => <Text > {item.temp.out.c} </Text>}

          keyExtractor={(item, index) => index}

</View>

    );
  }
}

Json

{
  "ts": 1530290929,
  "trend": {
    "val": -20,
    "text": "langsam fallend"
  },
  "baro": 1010.4310482000001,
  "temp": {
    "out": {
      "f": 85.9,
      "c": 29.9
    }
  },
  "hum": {
    "out": 29
  },
  "wind": {
    "speed": {
      "mph": 5,
      "kmh": 8
    },
    "avg": {
      "mph": 3,
      "kmh": 4.8
    },
    "dir": {
      "deg": 58,
      "text": "ONO"
    }
  },
  "rain": {
    "rate": 0,
    "storm": 0,
    "day": 0,
    "month": 100.33,
    "year": 451.358
  },
  "et": {
    "day": 176,
    "month": 480,
    "year": 1673
  },
  "forecast": {
    "val": 6,
    "rule": 45,
    "text": "Zunehmend wolkig bei gleichbleibender Temperatur."
  },
  "sun": {
    "uv": 1.3,
    "rad": 322,
    "rise": "4:25",
    "set": "20:37"
  }
}

谢谢!

1 个答案:

答案 0 :(得分:0)

我认为您正在尝试将道具传递给View。要正确执行此操作,请将代码更改为

<View data ={ this.state.dataSource }
      renderItem={({item}) => <Text > {item.temp.out.c} </Text>}
      keyExtractor={(item, index) => index}/>