繁体   English   中英

在React Native中解析对FlatList的JSON数组响应

[英]Parse JSON array response to FlatList in React Native

我愿意将上述JSON响应解析为FlatList,但无法弄清缺少的内容。 由于它没有键和值对,因此我不确定如何呈现它。

 {"list":["a","b","c","d"]} 

我的代码是...

 import React from 'react'; import { View, FlatList, Text } from 'react-native'; export default class Home extends React.PureComponent { constructor(props) { super(props); this.state = { dataSource: [] }; } async componentDidMount() { const response = await fetch('http://.../'); const responseJson = await response.json(); this.setState({ dataSource: responseJson.list }); } render() { return ( <View style={{ flex: 1, paddingTop: 20 }}> <FlatList data={this.state.dataSource} renderItem={({ item, index }) => <Text>{item[index]}</Text>} keyExtractor={(item, index) => index} /> </View> ); } } 

您的问题是因为您正在执行以下操作

renderItem={({ item, index }) => <Text>{item[index]]}</Text>}

item指的是a,b,c,d,但您正在做的a[index]b[index]显然是错误的

解决方案:

<FlatList
...
  renderItem={({ item }) => <Text>{item}</Text>}
...
/>

您不需要renderItem索引,因为该item已经分别是abcd

您不需要项目索引,请尝试以下代码,并让我知道。

 import React from 'react'; import { View, FlatList, Text } from 'react-native'; export default class Home extends React.PureComponent { constructor(props) { super(props); this.state = { dataSource: [] }; } async componentDidMount() { const response = await fetch('http://.../'); const responseJson = await response.json(); this.setState({ dataSource: responseJson.list }); } render() { return ( <View style={{ flex: 1, paddingTop: 20 }}> <FlatList data={this.state.dataSource} renderItem={({item}) => <Text>{item}</Text>} keyExtractor={this.state.dataSource.indexOf(item)} /> </View> ); } } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM