React-Native无法读取undefined的属性

时间:2018-04-07 12:17:49

标签: javascript react-native fetch state

原生开发者!我遇到了一些问题:我正在尝试发出GET请求,当我想显示它时,我得到错误:无法读取未定义的属性'door_state'。有什么可能是错的,你能解释一下吗?我的GetApartments课程:

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

class GetApartments extends Component{
  constructor(props){
      super(props);
      this.state = {
        apartments: []
      }
 }

  componentDidMount() {
      this.getApartmentsFromApi().then((res) => {
        this.setState(() => ({
          apartments : res
        }));
      });
  }

  async getApartmentsFromApi() {
    try {
      let response = await fetch(
    'http://ec2-13-59-148-153.us-east-2.compute.amazonaws.com:3000/api/flat'
      );
      let responseJson = await response.json();
      return responseJson;
    } catch (error) {
      console.error(error);
    }
  }

  render() {
    let door = this.state.apartments[0].door_state;
    return(
      <View> <Text>{door}</Text> </View>
    )
  }

}

这是我的公寓页面,我尝试显示数据:

export default class ApartmentsPage extends React.Component {

  render() {
    return(
      <View>
        <GetApartments />
      </View>
    )
  }
}

最诚挚的问候。

0 个答案:

没有答案