我正在尝试使用apikey
从服务器获取数据。我已经用此link创建了一些文档。使用文档的link,我无法在代码中列出项目。
从'react'导入React;导入{FlatList,ActivityIndicator,文字,查看}来自“ 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> ); } }
这里是来自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,