如何获取复杂的json到React Native Flatlist?



我试图从新闻API中获取API,但是格式对我来说很难从中提取数据。我曾尝试将json解析为数组,但仍然无法将数据获取到flatlist中。我有什么建议可以解决这个问题吗?谢谢你的帮助。我已经在世博会上建立了这个,可以在下面的链接上进行测试。下面是API类:

import React, {Component} from 'react';
import {Text, ActivityIndicator, FlatList} from 'react-native';
export default class API extends Component{
constructor(props){
super(props);
this.state = {
isLoading: true,
data: null
}
}

componentDidMount(){
fetch('https://newsapi.org/v2/top-headlines?country=my&category=sports&apiKey=73e8cdd9f6be475cb4a2d128bae3650c')
.then((response) => response.json())
.then((responseJson) => {
//tried to simplify the json(I'm not sure whether its right)
//var parsedjson = JSON.parse(responseJson);
//var myarray = parsedjson.articles;
this.setState({
isLoading: false,
data: responseJson//myarray,
})
})
.catch((error) => {
console.error(error);
});
}
_renderItem = ({item, index}) =>{
return(
//I think here's the problem. I've tried to use {item.articles.title}
<Text>{item.title}</Text>
)
}
render(){
if(this.state.isLoading){
return(
<ActivityIndicator style={{marginTop: 250}} size="large" color='white'/>
)
}else{
let {data, isLoading} = this.state;
return(
<FlatList
data={data}
renderItem={this._renderItem}
keyExtractor={(item,index)=> index.toString()}
/>
)
}
}
}

使用相同的方式,我设法获取API的格式,如

[
{
"id": "1",
"title": "GG",
"body": "the body here",
"image": "image link",
"link": null
}]

,但现在它不能工作当使用json格式像这样:

{
"status": "ok",
"totalResults": 38,
"articles": [
{
"source": {
"id": "the-washington-post",
"name": "The Washington Post"
},
"author": "Rachel Lerman, Cat Zakrzewski, Heather Kelly",
"title": "Apple"
}
]
}

在您的componentDidMount中,您有

componentDidMount(){
fetch('https://newsapi.org/v2/top-headlines?country=my&category=sports&apiKey=73e8cdd9f6be475cb4a2d128bae3650c')
.then((response) => response.json())
.then((responseJson) => {
//var parsedjson = JSON.parse(responseJson); 
// you don't need to parse the json here. It's already a JSON object.
this.setState({
isLoading: false,
data: responseJson, // here you can do either responseJson or responseJson.articles.
})
})
.catch((error) => {
console.error(error);
});
}

你不需要在JSON上使用JSON.parse()。你可以在MDN

阅读更多关于JSON解析的内容现在,在你的FlatList中,你有

<FlatList
data={data}
renderItem={this._renderItem}
keyExtractor={(item,index)=> index.toString()}
/>

Flatlistdataprop中,根据您设置的数据状态将数据更改为data.articles或仅data

如果你用过

this.setState({
isLoading: false,
data: responseJson,
})

您必须使FlatList的数据道具如下,

<FlatList
data={data.articles}
renderItem={this._renderItem}
keyExtractor={(item,index)=> index.toString()}
/>

或者如果您已将数据状态设置为

this.setState({
isLoading: false,
data: responseJson.articles,
})

你可以简单地保持FlatList现在的样子。

现在在你的_renderItem上,

_renderItem = ({item, index}) =>{
return(
<Text>{item.title}</Text>
)
}

应该是这样的。您不需要使用{item.articles.title},因为您已经为FlatList组件提供了articles数组。

你想从给定的json中获取什么,如果你在json中有多个日期,那么你必须传递位置。你必须这样写从路径中导入jsonObject然后如果你想得到文章数组然后写jsonObject。文章等

最新更新