map不是react-native中的函数

时间:2019-07-11 15:09:35

标签: react-native

我想从api获取一些数据并在我的应用程序中显示数据。这是我的代码     类AlbumList扩展了组件{

state = { albums: [] };

async componentWillMount() {
try {
  const data = await axios.get(
      'https://rallycoding.herokuapp.com/api/music_albums'
  );
  this.setState({ albums: data });
} catch (err) {
  console.error(err.message);
}
}

renderAlbums() {
  return this.state.albums.map(album => <Text>{album.title}</Text>);
}

render() {
return (
  <View>
    {this.renderAlbums()}
  </View>
 );
 }
 }

这将给出错误this.state.albums.map不是函数。 有什么办法解决这个问题?

1 个答案:

答案 0 :(得分:1)

发生错误“将其映射为非函数”是因为axios不返回数组。 Axios返回一个带有状态键,数据键的对象。

const data = await axios.get(
  'https://rallycoding.herokuapp.com/api/music_albums'
);
console.log(data);
console.log(data.data); // album data
this.setState({album: data.data});

在不等待的情况下使用

axios.get('https://rallycoding.herokuapp.com/api/music_albums')
  .then(response => {
    this.setState({ album: response.data });
  })
  .catch(error => {
    console.log(error);
  });

因此,您必须检查axios get返回的对象键“数据”。