React native:TypeError:Undefined不是函数(this.state.aalbums.map)



当我试图用genymotion作为模拟器运行它时,我遇到了这个错误。这是我的代码

import React, { Component } from 'react'; 
import { View, Text } from 'react-native';
import Axios from 'axios';
class AlbumList extends Component {
state={ albums: {} };

componentWillMount() {
Axios.get('https://rallycoding.herokuapp.com/api/music_albums')
.then(response => this.setState({ albums: response.data }));
}
renderAlbums() {
this.state.albums.map(album => <Text> { album.title } </Text>);
}
render() {
console.log(this.state);
return (
<View>
{this.renderAlbums()}
</View>
);
}
}  

export default AlbumList;

我是不是错过了什么?如果有人能帮我,请告诉我,我被困在这里了。

您最初将state.albums设置为一个空对象,但尝试调用map,它是一个数组方法。

还要确保来自api的response.data是一个数组。

最佳做法是在构造函数中初始化状态。

class AlbumList extends Component {
constructor(props) {
super(props);
this.state={
albums: []
}; 
}
...
}

最新更新