【问题标题】:fetch data in react native from mlab从 mlab 获取本地反应数据
【发布时间】:2020-01-17 10:49:27
【问题描述】:

我正在尝试学习使用apikey 从服务器获取数据。我用这个link 创建了一些文档。 使用我的文档的link,我无法在我的代码中列出项目。

从“反应”导入反应;导入 { FlatList,ActivityIndi​​cator, 来自'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> ); } }

【问题讨论】:

    标签: reactjs react-native backend mlab


    【解决方案1】:

    这是来自 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,
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-23
      • 1970-01-01
      • 1970-01-01
      • 2020-10-20
      • 2021-01-12
      • 1970-01-01
      • 2018-07-11
      • 1970-01-01
      相关资源
      最近更新 更多