通过React Native显示JSON数据-json数组

问题描述 投票:0回答:2

我正在尝试进行API调用以获取一些JSON数据并将其显示在我的React Native应用程序中,但不会将数据显示给实际的应用程序。我知道该调用可以工作,因为我已成功调用它并将其记录到控制台,并且看到了日志-我只是无法使其显示在我的代码的ReactNative部分中。

我认为这可能与JSON数据中包含数组的事实有关,我不确定如何解析它。这是我的JSON的样子:

{"resultCode":0,"message":"[{\"id\":0000000,\"entityType\":\"NONE\",,\"namePrefix\":\"\",\"nameFirst\":\"\",\"nameMiddle\":\"\",\"nameLast\":\Doe\",\"nameSuffix\":\"\",\"address1\":\"1234 TEST ST\",\"address2\":\"\",\"city\":\"CUPERTINO\",\"state\":\"CA\",\"zip\":\"11111\",\"country\":\"US\",\"physicalAddress1\":\"1234 TEST ST\",\"phoneNumbers\":[],\"addresses\":[],\"email1\":\"[email protected]\",\"gender\":\"EMPTY\",\"dob\":\"Oct 24, 2016, 12:00:00 AM\",\"occupation\":\"\",\"createdTimestamp\":\"Aug 26, 2019, 9:55:24 PM\",\"modifiedTimestamp\":\"Aug 26, 2019, 9:55:24 PM\"}]"}

基本上有两个字段resultcodemessage,但在message内部是一个包含更多JSON数据的数组。我知道这很丑陋,但这只是一个测试,这是我必须使用的。

我的React Native代码如下:

import React, { Component } from 'react';
import { Text, View, FlatList, StyleSheet } from 'react-native';

export default class App extends React.Component {
    constructor( props: {} ) {
    super(props);

     this.state = {
         isLoading: true,
         dataSource: []
     };
 }

 componentDidMount() {
     fetch("https://mytestapi.com/test.json")
     .then((response) => response.json())
     .then((responseJson) => {
         this.setState({
             isLoading: false,
             dataSource: responseJson
         });
     });
 }

 renderItem = ({item, index}) => {
     let { resultCode, message } = item;

     if (!message[0]) return null;
     let details = message[0];

     return (
         <View style={styles.container}>
             <Text style={styles.header}>Entity ID: {details.entityId}</Text>
         </View>
     );
 }

 keyExtractor = (item, index) => {
     return index.toString();
 }

 render() {
     return (
         <View style={{flex: 1}}>
             <FlatList
                 data={this.state.dataSource}
                 keyExtractor={this.keyExtractor}
                 renderItem={this.renderItem}
             />
         </View>
     );
 }
}

const style = StyleSheet.create({
  container: {
      paddingTop: 45,
      backgroundColor: '#F5FCFF',
  },
  header: {
      fontSize: 25,
      textAlign: 'center',
      margin: 10,
     fontWeight: 'bold'
  },
});

const fetchAndLog = async() => {
   const response = await fetch("https://my.testapi.com/test.json");
   const json     = await response.json();
   console.log(json);
}

fetchAndLog();

我知道调用成功,因为fetchAndLog函数成功登录到控制台,所以我在代码的React Native部分中显示JSON数据只是一个问题。我已经尝试过几次更改代码,但似乎无法使其打印出JSON的message部分,并且我已经使用this answerthis answer来尝试和提供帮助。

任何提示?

编辑:这是我尝试在应用程序中查看时遇到的错误:

Invariant Violation: Tried to get frame for out of range index NaN

This error is located at:
  in VirtualizedList (at FlatList.js:632)
  in FlatList (at App.js:45)
  in RCTView (at View.js:45)
  in View (at App.js:44)
  in App (at withExpoRoot.js:20)
  in RootErrorBoundary (at withExpoRoot.js:19)
  in ExpoRootComponent (at renderAPplication.js:35)
  in RCTView (at View.js:45)
  in View (at AppContainer.js:98)
  in RCTView (at View.js:45)
  in View (at AppContainer.js:115)
  in AppContainer (at renderApplication.js:34)
javascript json reactjs react-native
2个回答
0
投票

消息始终存在吗?回来时是否存在数据?我还要再添加几张支票:

 componentDidMount() {
   fetch("https://mytestapi.com/test.json")
   .then((response) => response.json())
   .then((responseJson) => {
     this.setState({
         isLoading: false,
         dataSource: responseJson || []
     });
  });
}

renderItem = ({item, index}) => {
     let { resultCode, message } = item;

     if (message == null || !message[0]) return null;
     let details = message[0];

     return (
         <View style={styles.container}>
             <Text style={styles.header}>Entity ID: {details.entityId}</Text>
         </View>
     );
 }

0
投票

好像您要传递一个对象作为FlatList数据源,但是您应该传递一个数组。

尝试:

<FlatList
     data={this.state.dataSource.message}
     keyExtractor={this.keyExtractor}
     renderItem={this.renderItem}
/>

...

renderItem = ({item, index}) => {

     return (
         <View style={styles.container}>
             <Text style={styles.header}>Entity ID: {item.id}</Text>
         </View>
     );
 }

如果您不打算显示数据数组,则应该使用FlatList之外的其他东西。另外,在该数据的任何地方都没有看到名为entityId的字段。

© www.soinside.com 2019 - 2024. All rights reserved.