2017-02-19 96 views
0

我正在使用fetch調用服務器的api,並且響應json文件返回一個未定義類型的響應。我想記錄迴應並將其呈現在屏幕上。React Native:抓取API調用返回不適當的響應

它我的源代碼:

'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

請幫幫我!

回答

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); 
     }); 

乾杯:)

+0

非常感謝,這工作,但這裏的問題是處理JSON對象! 好的,請給出一個處理高度嵌套的json對象的簡要描述,或者我可以幫助我更合適地實現rowHasChanged函數的任何鏈接。 –

+0

只要dataSource發生變化,它就會重新渲染,並且你的renderView的renderRow api會觸發來更新列表視圖 – Codesingh

+0

在你的renderRow()中,你將接受一個參數renderRow(rowData),之後你可以使用'。'簡化你的json數據。例如,如果你有一些關鍵的名字細節,並且在那個細節鍵裏有更多的鍵,比如'id','address'等,你可以通過rowData.detail.address獲取每一行的'地址'。 :) – Codesingh