简体   繁体   中英

React Native: Accessing JSON data

I'm using the fetch API to access the data and it turns out that when accessing this data which I have set in the data source it returns:

Warning : [TypeError: undefined is not an object(evaluating 'response.data.onwardflights')]

I am sure that I've fetched the data correctly as I have seen the data by printing it onto the console.

Here is the code for the same!

'use strict';

import React, {Component} from 'react';
import {StyleSheet, View, Text, ListView, ScrollView} from 'react-native';

const ds = new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2});

class BusList extends Component {

    constructor() {
    super();
    // const ds = new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2});
    this.state = {
      dataSource: ds.cloneWithRows([]),
      getData: []
    };
  }

    componentDidMount() {
        this.loadJSONData();
    }

    loadJSONData() {
        fetch('api')
          .then((response) => {
            this.setState({getData: response})
            this.setState({dataSource: ds.cloneWithRows(response.data.onwardflights)})
            return response.json()
          })
          .then((responseJSON) => {
                    console.log(responseJSON)
              return this.setState({dataSource: this.state.dataSource.cloneWithRows(responseJSON)});
          })
          .catch((error) => {
            console.warn(error);
          });
    }

    renderRow(rowData) {
        return (
            <View>
                <Text>{rowData.origin}</Text>
            </View>
        );
    }

    render() {
    return (
        <View>
            <ListView
                dataSource = {this.state.dataSource}
                enableEmptySections = {true}
                renderRow = {(rowData) => <Text>{rowData}</Text>}   
            />
        </View>
    );
  }
}

module.exports = BusList;

Any help will be appreciated!

Of course the response.data.onwardflights will be undefined because you haven't invoked the response.json() prior to reading the data. Invoke the method first, and only then read the data. Please read this article

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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