简体   繁体   English

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

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

I'm willing to parse the above JSON response to a FlatList, but I can't figure what I'm missing. 我愿意将上述JSON响应解析为FlatList,但无法弄清缺少的内容。 Since it does not have a key and value pair, I'm not sure how to render it. 由于它没有键和值对,因此我不确定如何呈现它。

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

My code is... 我的代码是...

 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> ); } } 

Your problem is because you're doing the below 您的问题是因为您正在执行以下操作

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

item is referring to a,b,c,d but you're doing a[index] , b[index] which clearly wrong item指的是a,b,c,d,但您正在做的a[index]b[index]显然是错误的

Solutions: 解决方案:

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

You don't need index for your renderItem because the item is already a , b , c , d respectively 您不需要renderItem索引,因为该item已经分别是abcd

You dont need item index, try the below code and let me know. 您不需要项目索引,请尝试以下代码,并让我知道。

 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