如何在React Native FlatList中加载复杂结构JSON的接口数据
问题解决
核心原因:你之前适配的API直接返回数组结构,可直接传入FlatList的data属性使用。但当前调用的新闻接口返回的是外层对象,实际的新闻列表数据存放在articles字段中,这是代码无法正常运行的核心原因。
需调整的代码逻辑:
- fetch返回的response调用
json()方法后已经是标准JS对象,不需要额外调用JSON.parse二次解析,重复解析会触发报错 - setState时不需要将整个返回对象赋值给data,只需要取
responseJson.articles这个数组字段赋值 - 初始化state时可以将data默认设为空数组,避免空值判断异常
- _renderItem中的item就是单条新闻对象,直接取
item.title即可,不需要再加一层articles字段
修改后完整代码:
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: [] // 初始化改为空数组 } } componentDidMount(){ fetch('https://newsapi.org/v2/top-headlines?country=my&category=sports&apiKey=73e8cdd9f6be475cb4a2d128bae3650c') .then((response) => response.json()) .then((responseJson) => { this.setState({ isLoading: false, data: responseJson.articles // 直接取articles数组 }) }) .catch((error) => { console.error(error); }); } _renderItem = ({item, index}) =>{ return( <Text>{item.title}</Text> ) } render(){ if(this.state.isLoading){ return( <ActivityIndicator style={{marginTop: 250}} size="large" color='white'/> ) }else{ let {data} = this.state; return( <FlatList data={data} renderItem={this._renderItem} keyExtractor={(item,index)=> index.toString()} /> ) } } }
内容的提问来源于stack exchange,提问作者fahmijaafar
相关产品推荐
相关产品推荐

