responseJson未定义

时间:2019-03-21 01:02:48

标签: javascript react-native

这是用于从API提取JSON数据的代码。我想做的是在我的平面列表中打印各种药物的名称,然后使该对象可单击,以便在下一页上显示有关此对象的更多信息。我可以正确接收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'
  }
})

JSON Response alert in Android Emulator

JSON Response in Postman

1 个答案:

答案 0 :(得分:2)

doc之后,我看到的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