简体   繁体   中英

error in react Native while show featch json data in render()

I'm new to React - native development. I have this json data need to show in render() using {this.state.data.min.en}

{
  "status": true,
  "message": "good",
  "data": {
    "min": {
      "sin": "text",
      "en": " text",
      "ta": "text",
      "ownere": "  text"
    }
  }
}

The code:

import React, { Component } from "react";
import {
  Platform,
  StyleSheet,
  Text,
  View,
  AppRegistry,
  Alert
} from "react-native";
import { Card } from "react-native-elements";

export default class Home extends Component {
  constructor() {
    super();
    this.state = {
      data: []
    };
  }

  handlePress = async () => {
    fetch("http://xxx.xx.xx.xx/index.php/testCV/home", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      }
    })
      .then(response => response.json())
      .then(responseJson => {
        this.setState({ data: responseJson.data });
      })
      .catch(error => {
        console.error(error);
      });
  };

  componentDidMount() {
    this.handlePress();
  }

  render() {
    return (
      <View>
        <Card>{this.state.data.min.en}</Card>
      </View>
    );
  }
}

AppRegistry.registerComponent("Home", () => Home);

I try it using above code but when i run it i get this error. I try to find way to fix it but no luck.

在此处输入图片说明

It's very grateful someone can help me out with this error. Thanks

You are defaulting your data to an empty array, so when you write this.state.data.min you will get undefined , and then trying to access en on that will give rise to your error.

You could eg default the data to null , and wait until your data has been loaded before rendering it.

Example

export default class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: null
    };
  }

  // ...

  render() {
    const { data } = this.state;

    if (data === null) {
      return null;
    }

    return (
      <View>
        <Card>{data.min.en}</Card>
      </View>
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM