【发布时间】:2020-02-19 10:20:41
【问题描述】:
我是 react native 的初学者。我有个问题。 我正在尝试从反应本机的 api 获取数据,但我无法做到这一点。没有编译器错误或警告消息,只是模拟器给出了空白页。
这是我的代码:
import React from 'react';
import { FlatList, ActivityIndicator, Text, View } from 'react-native';
export default class FetchExample extends React.Component {
constructor(props){
super(props);
this.state ={ isLoading: true}
}
componentDidMount(){
return fetch("https://apidojo-yahoo-finance-v1.p.rapidapi.com/market/get-summary?region=US&lang=en", {
"method": "GET",
"headers": {
"x-rapidapi-host": "apidojo-yahoo-finance-v1.p.rapidapi.com",
"x-rapidapi-key": "********"
}
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson.data,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
}
render(){
if(this.state.isLoading){
return(
<View style={{flex: 1, padding: 20}}>
<ActivityIndicator/>
</View>
)
}
return(
<View style={{flex: 1, paddingTop:20}}>
<FlatList
data={this.state.dataSource}
renderItem={({item}) => <Text>{item.region}, {item.lang}</Text>}
keyExtractor={({id}, index) => id}
/>
</View>
);
}
}
希望得到您的帮助。
【问题讨论】:
-
您不必返回您的
componentDidMount。将dataSource添加到状态并添加一个空的初始值数组。如果您的 fetch 方法返回任何内容,请尝试控制台日志。也许你的 API 调用有问题 -
控制台日志中没有数据。
-
所以因为没有数据,所以列表会是空的...在邮递员或失眠中运行相同的API调用,我认为你的API调用是错误的。
标签: javascript react-native fetch