![](/img/trans.png)
[英]Unhandled Promise Rejection: TypeError: undefined is not an object (evaluating 'data.date')
[英][Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'this.state.result.map')]
[未處理的 promise 拒絕:TypeError:未定義不是 object(評估 'this.state.result.map')]。 每當我嘗試從 api 獲取數據時,都會出現此錯誤。 在下面的代碼中,我使用了 val.Global,其中 Global 是所有數據的標題。 誰能告訴我的代碼有什么問題?
import React from 'react';
import {View, Text, ActivityIndicator, StyleSheet, FlatList} from 'react-native';
export class mainScreen extends React.Component{
constructor(props){
super(props);
this.state = {
isloading: true,
result: []
}
}
componentDidMount(){
return fetch('https://api.covid19api.com/summary')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isloading: false,
result: responseJson.covid
})
})
}
render(){
if(this.state.isloading){
return (
<View style={styles.container}>
<ActivityIndicator/>
</View>
)
}else{
let covid = this.state.result.map((val, key) => {
return <View key={key} style={styles.item}><Text>{val.Global}</Text></View>
});
return(
<View style={styles.container}>
{covid}
</View>
);
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
item: {
flex: 1,
alignSelf: 'stretch',
margin: 10,
alignItems: 'center',
justifyContent: 'center'
}
});
您的 API 調用返回此:
{
"Global": {
"NewConfirmed": 214569,
"TotalConfirmed": 14506757,
"NewDeaths": 4029,
"TotalDeaths": 606157,
"NewRecovered": 104134,
"TotalRecovered": 8149310
},
"Countries": [
{
"Country": "Afghanistan",
"CountryCode": "AF",
"Slug": "afghanistan",
"NewConfirmed": 174,
"TotalConfirmed": 35475,
"NewDeaths": 17,
"TotalDeaths": 1181,
"NewRecovered": 361,
"TotalRecovered": 23634,
"Date": "2020-07-20T13:49:18Z",
"Premium": {}
},
...
在您的組件中,您正在嘗試檢索不存在的“covid”字段...您需要像這樣保存 API 數據:
this.setState({
isloading: false,
result: responseJson
})
並以這種方式更改您的渲染:
render() {
const { loading, result } = this.state;
if (loading) {
return (
<View style={styles.container}>
<ActivityIndicator/>
</View>
);
}
//If you want to show total recovered for global
return (<View key={key} style={styles.item}><Text>{val.Global.TotalRecovered}</Text></View>);
//If you want to show global recovered for each country
const covid = result.Countries.map(country => (<View key={key} style={styles.item}><Text>{country.TotalRecovered}</Text></View>));
return (
<View style={styles.container}>
{covid}
</View>
);
}
由於您試圖通過一個不存在的表來 go ,因此該錯誤已被捕獲。
我正在做一個類似的項目。 猜猜這應該足夠了
const covid = result.Countries.map((country, key) => {
return (<View key={key} style={styles.item}><Text>{country.TotalRecovered}</Text></View>);
})
return (
<View style={styles.container}>{name}</View>
)
猜猜這應該足夠了!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.