【发布时间】:2019-12-26 03:46:00
【问题描述】:
我有两个组件,一个称为 homeScreen,第二个是卡片,我在 homeScreen 中获取数据,在我通过 props 将状态发送到我的卡片组件后,我将其设置为 state。 现在我的卡组件应该根据我发送给它的数据生成 9 张卡,所以我做了映射,我收到了这个错误 类型错误:无法读取未定义的属性“0”。
我尝试在 Card 组件中 console.log 道具,我可以看到数据,但由于某种原因地图无法正常工作
卡片.js
const Card = props => {
Array.from({length: 9}).map((i, index) => {
console.log(props);
return (
<View style={{flex: 1}}>
<Text style={{flex: 1, backgroundColor: 'red'}}>
{props.title[1] ? `${props.title[index]}` : 'Loading'}
</Text>
<Text style={{flex: 1, backgroundColor: 'blue'}}>{props.rating[index]}</Text>
</View>
);
});
};
export default Card;
homeScreen.js
export default class HomeScreen extends React.Component {
state = {
title: [],
image: [],
rating: [],
isLoading: true,
};
componentDidMount() {
this.getData();
}
titleSend = () => {
if (!this.state.isLoading) {
{
Array.from({length: 9}).map((i, index) => {
return this.state.title[index];
});
}
}
};
imageSetter = () => {
Array.from({length: 9}).map((i, keys) => {
return (
<Image
key={keys}
style={{width: 50, height: 50, flex: 1}}
source={{uri: this.state.image[keys]}}
/>
);
});
};
getData = () => {
const requestUrls = Array.from({length: 9}).map(
(_, idx) => `http://api.tvmaze.com/shows/${idx + 1}`,
);
const handleResponse = data => {
const shows = data.map(show => show.data);
this.setState({
isLoading: false,
title: shows.map(show => show.name),
image: shows.map(show => show.image.medium),
rating: shows.map(show => show.rating.average),
});
// console.log(this.state);
};
const handleError = error => {
this.setState({
isLoading: false,
});
};
Promise.all(requestUrls.map(url => axios.get(url)))
.then(handleResponse)
.catch(handleError);
};
render() {
const {isLoading, title, image, rating} = this.state;
if (isLoading) {
return <ActivityIndicator size="large" color="#0000ff" />;
}
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<ScrollView style={{flex: 1, backgroundColor: 'red'}}>
<Card title={this.state.title} />
</ScrollView>
<Text>here images</Text>
</View>
);
}
}
【问题讨论】:
-
在
map之外尝试您的console.log。在任何情况下,您都试图在您的卡片中访问props.rating,但根据您提供的代码,您只是将title传递给卡片 -
问题似乎出在
props.rating[index]- 当你使用Card时,你只传递一个title属性,而不是rating一个
标签: javascript arrays reactjs react-native array.prototype.map