首页 > 解决方案 > 解析 json 在本机平面列表中做出反应

问题描述

我正在尝试在 Flatlist 中呈现数据,但它没有任何解决方案?

我的代码:

import React from 'react'
import { ActivityIndicator,  FlatList, Text, View  } from 'react-native'
import styles from '../components/style.js'

export default class Nachrichten extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      nachrichtenapidata: [],
      loading: true
    };
  }

  async componentDidMount() {
    try {
        const nachrichtenApiCall = await fetch(URL);
        const nachrichten = await nachrichtenApiCall.json();
        this.setState({nachrichtenapidata: nachrichten.data, loading: false});
        console.log(this.state.nachrichtenapidata);
    } catch(err) {
        console.log("Error fetching data-----------", err);
    }
  } 
  render() {
    if (this.state.isLoading) {
      return (
        <View style={{ flex: 1, padding: 20 }}>
          <ActivityIndicator />
        </View>
      );
    }
    return (
      <View style={{ flex: 1, paddingTop: 20 }}>
        <FlatList
          data={this.state.nachrichtenapidata}
          renderItem={({ item }) => (
            <Text>
              -> {item}
            </Text>
          )}
          keyExtractor={(index) => index}
        />
      </View>
    );
  }
}

我的输出是:

在此处输入图像描述

任何解决方案-我认为我在做一些愚蠢的事情,但看不到它....?

Tnx 全部求助!

标签: react-native

解决方案


您可以使用 JSON.parse() :

async componentDidMount() {
    try {
        const nachrichtenApiCall = await fetch(URL);
        const nachrichten = await nachrichtenApiCall.json();
        const json = JSON.parse(nachrichten);
        this.setState({
          nachrichtenapidata: json.data, 
          loading: false
        });
        console.log(this.state.nachrichtenapidata);
    } catch(err) {
        console.log("Error fetching data-----------", err);
    }
  } 

您确定服务器正在返回有效的 json 响应吗?


推荐阅读