React Native说类型错误:undefined不是一个对象(正在评估“ this.props.sprites.front_default”)。由于警告显示了API中的详细信息以及访问“ id”和“ name”时,API调用已成功工作'它可以工作,但是当尝试使用'sprites'时总是会出错。我尝试仅使用API调用并使用了sprites,并且可以正常工作,但是当在该项目中使用时根本无法工作...几天无法解决这个小问题... 这是代码示例。
<ScrollView style = {styles.container}>
<View style = {styles.imageView}>
<View style = {styles.dataView}>
<Text>ID:{this.props.data.id}name:{this.props.data.name} </Text>
<Image source = {{uri: this.props.data.sprites.front_default}}/>
</View>
</View>
</ScrollView>
这是API数据获取的searchbody页面。
## **searchbody.js** ##
```import React, { Component } from 'react';
import { View, Text, ScrollView, StyleSheet, Image } from 'react-native';
import axios from 'axios';
import SearchBodyTemplate from './searchbodytemplate';
export default class SearchBody extends Component {
static navigationOptions = {
header: null
}
state = {
isLoading: true,
data: {},
pokeSearch: `https://pokeapi.co/api/v2/pokemon/${this.props.navigation.state.params.value.toLowerCase()}`,
}
componentWillMount(){
var self = this;
axios.get(`${this.state.pokeSearch}`)
.then(function(response){
console.warn(response.data)
self.setState({data:response.data});
})
.catch(function(error){
console.log(error)
})
}
renderBody = () => {
return <SearchBodyTemplate data={this.state.data}/>
}
render() {
return (
<ScrollView style = {styles.container}>
<View style = {styles.imageView}>
{this.renderBody()}
</View>
<View style = {styles.dataView}>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
marginTop: 24,
backgroundColor: 'green',
flex: 1
},
imageView: {
height: 250,
width: '100%',
backgroundColor: 'red'
},
dataView: {
backgroundColor: 'blue',
height:600,
width:'100%'
}
})```
这是searchbodytemplate,这是一个自定义组件,用于将数据从“ searchbody”传递到“ searchbodytemplate”
## **searchbodytemplate.js** ##
```import React, { Component } from 'react';
import { View, StyleSheet, ScrollView, Text, Image } from 'react-native';
export default class SearchBodyTemplate extends Component {
render() {
return (
<ScrollView style = {styles.container}>
<View style = {styles.imageView}>
<View style = {styles.dataView}>
<Text>ID:{this.props.data.id}name:{this.props.data.name} </Text>
<Image source = {{uri: this.props.data.sprites.front_default}}/>
<Text>jhfukfgkthf</Text>
</View>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: 'green',
height:400,
width: 400
},
imageView: {
flex: 1,
backgroundColor: 'red'
},
dataView: {
flex: 3,
backgroundColor: 'green'
}
})```