javascript - responseJson 未定义

标签 javascript react-native

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

我的 flatlist 没有抛出任何错误,它只是不显示任何东西。我不确定此时还可以尝试什么。

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

最佳答案

关注doc我看到的 data 属性是一个数组。你应该像这样setState of 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

关于javascript - responseJson 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55272312/

相关文章:

javascript - Angular 2 DI 编码到接口(interface)

javascript - Analytics 脚本与淡入效果是否冲突?

javascript - D3.js 中的简单散点图示例?

react-native - 获得了屏幕 'component' 的 'children' 和 'Search' Prop 。你只能通过其中之一

react-native - 创建 react-native 项目时出现命令行错误

react-native - 每 x 秒更新一次状态

javascript - 使用 templateUrl 的 angularjs 指令 - 初始化序列

javascript - 在 Backbone.js 事件中实现切换

react-native - 如何更新已保存的项目 AsyncStorage

javascript - React-Native Firebase 使用 FlatList 显示对象数组