首页 > 解决方案 > responseJson 未定义

问题描述

这是我从 API 获取 JSON 数据的代码。我要做的是在我的 Flatlist 中打印各种药物的名称,然后使该对象可点击,以便我可以在下一页上显示有关它的更多信息。我可以正确接收 JSON 数据,但我的问题在于显示它。我的第一个警报显示了我的药物数组中的内容(两种药物),但是当我尝试显示这些名称时,我得到“未定义”,但显然有一个名为“名称”的字段与数据相关联。

我的平面列表没有抛出任何错误,它只是不显示任何内容。我不确定此时还可以尝试什么。

import React from 'react'
import {
  View,
  Text,
  Button,
  StyleSheet,
  FlatList,
  ActivityIndicator,
  AsyncStorage
} from 'react-native'
import Swipeout from 'react-native-swipeout';

import { goToAuth } from '../../helpers/Navigation'
import { Navigation } from 'react-native-navigation';

import { USER_KEY, USERID_KEY, USERNAME, PASSWORD, API_URL } from '../../helpers/Config'
import { refreshToken } from '../../helpers/Helper'

export default class Medication extends React.Component {
  constructor(props) {
    super(props);

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



  static get options() {
    return {
      topBar: {
        title: {
          text: 'Medication'
        },
      }
    };
  }

  componentDidMount() {

  }

  getMedications = async () => {
    // used to assign the medication to the specific individual
    const userID = await AsyncStorage.getItem(USERID_KEY);

    // used to access the protected links
    const userToken = await AsyncStorage.getItem(USER_KEY);


    fetch(API_URL + '/medications/all/' + userID, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'x-access-token': userToken
      },
    })
      .then((response) => response.json())
      .then((responseJson) => {
        alert(responseJson.status);
        alert(responseJson.message);
        // displays all medication data
        alert(JSON.stringify(responseJson.data.medications)); 
        // should display the names, displays undefined
        alert(JSON.stringify(responseJson.data.medications.name));
        this.setState({
          isLoading: false,
          dataSource: responseJson,
        });
      })
      .catch((error) => {
        console.error(error);
      });
  }

  logout = async () => {
    try {
      await AsyncStorage.removeItem(USER_KEY)
      goToAuth()
    } catch (err) {
      console.log('error signing out...: ', err)
    }
  }

  render() {

    if (this.state.isLoading) {
      return (
        <View style={{ flex: 1, padding: 20 }}>
          <ActivityIndicator />
        </View>
      )
    }

    return (
      <View style={styles.container}>



        <FlatList>
          data={this.state.dataSource}
          renderItem={({ item }) => <Text>{item.data.medications.name}</Text>}
          keyExtractor={(item, index) => index}
        </FlatList>

        <Button
          onPress={this.logout}
          title="Sign Out"
        />
        <Button
          onPress={() => {
            Navigation.push(this.props.componentId, {
              component: {
                name: 'MedicationDetailScreen',
              }
            });
          }}
          title="View Medication Detail Screen"
        />
        <Button
          onPress={() => {
            Navigation.push(this.props.componentId, {
              component: {
                name: 'AddMedicationScreen',
              }
            });
          }}
          title="View Add Medication Screen"
        />
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  }
})

Android 模拟器中的 JSON 响应警报

Postman 中的 JSON 响应

标签: javascriptreact-native

解决方案


按照我看到的属性是一个数组的文档。data你应该setState喜欢dataSource这个

this.setState({
      isLoading: false,
      dataSource: responseJson.data.medications,
    });

并且因为responseJson.data.medications是一个数组,所以你不能得到name一个项目的属性。您必须确定要name首先获得的项目。一定是

alert(JSON.stringify(responseJson.data.medications[0].name)) // For example the first item

推荐阅读