我已经在mysql中创建了一个表,用于一些新闻数据。它包括标题,主体和图像链接。该文件保存在example.com/api/news.php上,并通过链接将导致一个数组,类似于这样:
[{"id":"1","title":"News Title 1","body":"Body 1","date":"2020-12-01","image":"Image 1","link":"Link 1"},{"id":"2","title":"Title 2","body":"Body 2","date":"2020-12-17","image":"Image 2","link":"https:\/\/google.com"},{"id":"3","title":"Title 3","body":"Body 3","date":"2020-12-24","image":"Image 3","link":""}]
字符串
在react native中,我尝试通过以下示例来获取:
constructor(props){
super(props);
this.state = {
isLoading: true,
data: null
}
}
componentDidMount(){
return fetch('https://example.com/api/news.php')
.then((response) => response.json())
.then((json) => {
this.setState({
isLoading: false,
data: json.id,
})
})
.catch((error) => {
console.error(error);
});
}
render(){
if(this.state.isLoading){
return(
<View style={styles.container}>
<ActivityIndicator/>
</View>
)
}else{
return(
<View style={styles.container}>
<Text>Content Loaded!</Text>
</View>
)
}
}
型
然而,活动指示器继续运行。而当我尝试使用https://reactnative.dev/movies.json示例中的原始API链接时,它工作正常。我可以知道是什么问题阻止了JSON的读取。感谢您的指导。
1条答案
按热度按时间ltskdhd11#
从代码中删除
return
,可能会得到一个错误的响应,请尝试在错误中重置isLoading
状态,如字符串