簡體   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