React Native:Fetch api调用返回不适当的响应

时间:2017-02-19 17:48:54

标签: javascript json react-native fetch

我正在使用fetch对服务器进行api调用,而响应json文件正在返回未定义类型的响应。我想记录响应并在屏幕上呈现它。

我的源代码:

'use strict';

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

var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

class BusList extends Component {

    constructor() {
        super();
        const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.state = {
            dataSource: ds.cloneWithRows(['row 1', 'row 2']),
        };
    }

    componentDidMount() {
        this.loadJSONData();
    }

    loadJSONData() {
        fetch('my_api!')
      .then((response) => {
        return response.json()
      })
      .then((responseJSON) => {
          return this.setState({dataSource: this.state.dataSource.cloneWithRows(responseJSON)});
      })
      .catch((error) => {
        console.warn(error);
      });
}

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

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

module.exports = BusList;

但是,当我尝试记录它时,我得到以下log

请帮助我!

1 个答案:

答案 0 :(得分:0)

我认为不使用任何包装器而不是将其转换为json对象会使其变得非常复杂。你可以这样做:

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

 loadJSONData() {
        fetch('my_api!', {
            method: 'get',
            dataType: 'json',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
    })
      .then((response) => {
        this.setState({getData:response})
//putting response inside listview directly or you can put this.state.getData 
        this.setState({dataSource:ds.cloneWithRows(response)})
      })
      .catch((error) => {
        console.warn(error);
      });

干杯:)