从mlab本地获取反应数据

时间:2018-11-03 22:33:33

标签: reactjs react-native backend mlab

我正在托盘化以使用apikey学习从服务器获取数据。我与此https://facebook.github.io/react-native/movies.json创建相同的文档。我的文档链接https://api.mlab.com/api/1/databases/ibrhmklnc/collections/kitap?apiKey=xRw1H6NNZZnyeZArU5L8oUoVcsFb6tpf但是我无法在代码中列出项目。

  1. import React from 'react'; import { FlatList, ActivityIndicator, Text, View } from 'react-native';

    export default class FetchExample extends React.Component {
    constructor(props){ super(props); this.state ={ isLoading: true} }

    componentDidMount(){ return fetch('https://api.mlab.com/api/1/databases/ibrhmklnc/collections/kitap?apiKey=xRw1H6NNZZnyeZArU5L8oUoVcsFb6tpf') .then((response) => response.json()) .then((responseJson) => { this.setState({ isLoading: false, dataSource: responseJson.movies, }, function(){ }); }) .catch((error) =>{ console.error(error); }); }

    render(){

    if(this.state.isLoading){ return( <View style={{flex: 1, padding: 20}}> <ActivityIndicator/> </View> ) } return( <View style={{flex: 1, paddingTop:20}}> <FlatList data={this.state.dataSource} renderItem={({item}) => <Text>{item.title}, {item.releaseYear}</Text>} keyExtractor={({id}, index) => id} /> </View> ); } }

2 个答案:

答案 0 :(得分:0)

为什么要将空函数添加到setState?

答案 1 :(得分:0)

这是API的完整响应

[
    { 
        _id: { '$oid': '5be7260efb6fc072d46759b5' },
        movies: [ 
            { id: '1', title: 'Star Wars', releaseYear: '1977' },
            { id: '2', title: 'Back to the Future', releaseYear: '1985' },
            { id: '3', title: 'The Matrix', releaseYear: '1999' },
            { id: '4', title: 'Inception', releaseYear: '2010' },
            { id: '5', title: 'Interstellar', releaseYear: '2014' } 
        ] 
    }
]

如您所见,API响应是一个数组。因此,为了获取电影列表,您应该将dataSource设置如下:

dataSource: responseJson[0].movies,
相关问题