react-native - 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;
我错过了什么吗?如果有人可以帮助我,请告诉我,我被困在这里。
解决方案
您最初将 state.albums 设置为一个空对象,但您尝试调用 map 这是一个数组方法。
还要确保来自您的 api 的 response.data 是一个数组。
最佳实践是在构造函数中初始化状态。
class AlbumList extends Component {
constructor(props) {
super(props);
this.state={
albums: []
};
}
...
}
推荐阅读
- python - 从 IntegrityError 异常中获取密钥
- node.js - 节点 sqlite3:试图编写一个函数来返回一个行数组
- python - 如何对具有多特征的时间序列数据进行切片以获得连续图包含[训练+测试+预测]?
- r - 将单行中的数据放入多行
- php - YITH WooCommerce 愿望清单:帮我在侧边栏小部件和愿望清单管理区域中显示第一个项目/产品缩略图?
- ios - 在 Swift 中重试 firebase 令牌
- powershell - 替换连接字符串中的数据源
- javascript - 为什么异步等待代码中的捕获不触发?
- javascript - Dygraphs:系列的一部分到单独的图例中
- java - Eclipse Spring Boot - 在 HibernateJpaAutoConfiguration 和 CacheAutoConfiguration 之间检测到自动配置周期