简体   繁体   English

从JSON检索的render()中以return()显示数据

[英]Display data in return() from JSON retrieved render()

So I'm having a problem displaying data retrieved from an API as JSON. 所以我在显示从API检索到的数据作为JSON时遇到问题。 Below is the code. 下面是代码。 When I try to display the values in the render function, it doesn't display as it is undefined. 当我尝试在render函数中显示值时,由于未定义,所以不会显示。

import React, { Component } from 'react';

class Test extends Component {

render() {
    var request = require("request");
    var urlCardName = encodeURIComponent(this.props.card.card_name);
    var url = "./query.php?cardName=" + urlCardName;
    request({
        url: url,
        json: true
    }, function (error, response, body) {
        if (!error && response.statusCode === 200) {
            var cardResponse = JSON.stringify(body);
            var cardName = body.cardName.toString();
            var cardCount = body.cardCount.toString();
            console.log(cardCount);
        }
    })

    return(<div>
        Card Count: {cardCount}
        Card Name: {cardName}
    </div>);
}
}
export default Test;

The problem is that I don't think I fully understand how to take variables from JSON and display them as strings in the render function. 问题是我不完全了解如何从JSON中获取变量并将其显示为render函数中的字符串。

How can I display these values? 如何显示这些值?

Thanks! 谢谢!

1- You will need to save data from api into component state, and in react once you update the component state, component will render again and you will be able to see your data. 1-您将需要将api中的数据保存到组件状态,并且在更新组件状态后做出反应,组件将再次呈现,您将能够看到您的数据。

It is better to read more about React and component state 最好阅读更多有关React和组件状态的信息

2- You will need to move your request call to componentDidMount lifecycle function, this function will be called directly after the component is mounted, and you can update the component state inside this function, also it is critical to avoid updating state inside render function as it will end up with infinite render calls 2-您需要将请求调用移至componentDidMount生命周期函数,该函数将在组件安装后直接调用,并且您可以在此函数内更新组件状态,避免在render函数内更新状态也很重要,因为最终将导致无限次的渲染调用

It is also good to read more about component lifecycle 阅读更多有关组件生命周期的信息也很好

Finally you can try the following: 最后,您可以尝试以下操作:

import React, { Component } from 'react';

class Test extends Component {
  constructor(props) { 
    super(props);
    this.state = {
      cardName: '',
      cardCount: '',
    };
  }

  componentDidMount() {
    var request = require("request");
    var urlCardName = encodeURIComponent(this.props.card.card_name);
    var url = "./query.php?cardName=" + urlCardName;
    request({
        url: url,
        json: true
    }, function (error, response, body) {
        if (!error && response.statusCode === 200) {
            var cardResponse = JSON.stringify(body);
            this.setState( cardName: body.cardName.toString());
            this.setState( cardCount: body.cardCount.toString());
        }
    })
  }

  render() {
    return(<div>
        Card Count: {this.state.cardCount}
        Card Name: {this.state.cardName}
    </div>);
  }
}
export default Test;

By standards, you put AJAX requests in componentDidMount and update the state from there. 按照标准,您将AJAX请求放入componentDidMount并从那里更新状态。

import React, {Component} from 'react';
import request from 'request';

class Test extends Component {

    constructor(props) {

        super(props);

        this.state = {
            data: null // empty data
        }

    }

    componentDidMount(){

        var urlCardName = encodeURIComponent(this.props.card.card_name);
        var url = "./query.php?cardName=" + urlCardName;
        request({
            url: url,
            json: true
        }, (error, response, body) => {
            if (!error && response.statusCode === 200) {
                var cardResponse = JSON.stringify(body);
                var cardName = body.cardName.toString();
                var cardCount = body.cardCount.toString();

                // Update the state
                this.setState( { cardName, cardCount } );
            }
        })

    }

    render() {

        // Object destructing 
        let { cardName, cardCount } = this.state;

        return (
            <div>
                Card Count: {cardCount}
                Card Name: {cardName}
            </div>
        );
    }
}
export default Test;

It depends. 这取决于。 If you don't want that data to live within its own component (ex. <CardCount /> ), you can wrap cardCount in <h1> tags like: <h1>{cardCount}</h1> . 如果您不希望这些数据存在于其自身的组件中(例如<CardCount /> ),则可以将cardCount包装在<h1>标记中,例如: <h1>{cardCount}</h1>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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