【问题标题】:error in react Native while show featch json data in render()在render()中显示featch json数据时反应本机错误
【发布时间】:2018-07-15 09:32:56
【问题描述】:

我是 React 的新手 - 原生开发。我有这个 json 数据需要使用 {this.state.data.min.en}

在 render() 中显示
{
  "status": true,
  "message": "good",
  "data": {
    "min": {
      "sin": "text",
      "en": " text",
      "ta": "text",
      "ownere": "  text"
    }
  }
}

代码:

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);

我尝试使用上面的代码,但是当我运行它时,我得到了这个错误。我试图找到解决它的方法,但没有运气。

非常感谢有人能帮我解决这个错误。 谢谢

【问题讨论】:

    标签: javascript android reactjs react-native android-emulator


    【解决方案1】:

    您将数据默认为空数组,因此当您写入this.state.data.min 时,您将得到undefined,然后尝试访问en 将导致您的错误。

    你可以例如默认datanull,等到你的数据加载完毕再渲染。

    示例

    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>
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-04-09
      • 1970-01-01
      • 1970-01-01
      • 2020-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-29
      相关资源
      最近更新 更多