首页 > 解决方案 > React-native : TypeError : Undefined is not a function (this.state.albums.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;

我错过了什么吗?如果有人可以帮助我,请告诉我,我被困在这里。

标签: react-native

解决方案


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

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

最佳实践是在构造函数中初始化状态。

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

推荐阅读