最近我一直在尝试将我的js链接到组件文件夹,但是突然出现了问题。第一个问题是参照错误,这是因为我在导入部分犯了错字错误。但是随后,在第二次通过运行模拟器的尝试中,我得到了“类型错误:未定义不是对象(props.albums.title)”
这是我的Card.js
import React from 'react';
import { View } from 'react-native';
const Card = (props) => {
return (
<View style={styles.containerStyle}>
{props.children}
</View>
);
};
const styles = {
containerStyle: {
borderWidht: 1,
borderRadius: 2,
borderColor: '#ddd',
borderBottomWidth: 0,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 2,
elevation: 1,
marginLeft: 5,
marginRight: 5,
marginTOp: 10
}
};
export default Card;
这是AlbumDetail
import React from 'react';
import { Text } from 'react-native';
import Card from './Card';
const AlbumDetail = (props) => {
return (
<Card>
<Text>{props.album.title}</Text>
</Card>
);
};
export default AlbumDetail;
这是AlbumList
import React, { Component } from 'react';
import { View } from 'react-native';
import axios from 'axios';
import AlbumDetail from './AlbumDetail';
class AlbumList extends Component {
state={ albums: [] };
componentWillMount() {
axios.get('https://rallycoding.herokuapp.com/api/music_albums')
.then(response => this.setState({ albums: response.data }));
}
renderAlbums() {
return this.state.albums.map(album => <AlbumDetail key={album.title} record={album} />);
}
render() {
console.log(this.state);
return (
<View>
{this.renderAlbums()}
</View>
);
}
}
export default AlbumList;
答案 0 :(得分:0)
您必须捕获由数组生成的错误'undefined'。您在状态中声明空数组。
答案 1 :(得分:-1)
renderAlbums(){
if(this.state.albums=='undefined'){
//handle Error
}else{
return this.state.albums.map(album => <AlbumDetail key={album.title} record={album} />)
}