首页 > 解决方案 > div 上 Const 的 ReactJS 值

问题描述

我是 react 新手,有一个简单的应用程序,如下所示:

在此处输入图像描述

我对这个应用程序的目的是使用Spring Boot REST 服务并在我的反应应用程序上打印数据json 。

我在本教程之后实现了这一点:https ://github.com/marmelab/restful.js/tree/master

但现在我遇到了一个简单的问题,不知道如何在 html 标签上打印值,这是我的代码示例:

import React from 'react';
import request from 'request';
import restful, { requestBackend } from 'restful.js';

const api = restful('http://someUrl/v1/mobile', requestBackend(request));
const totals = api.one('statusOrders',1); //organizationID = 1

totals.get().then((response) => {
    const requestBody = response.body();
    const totalsOrders = requestBody.data(); /*Need to print this on the <div>**/
})

class RestGps extends React.Component {
    render(){
        return(
            <div className="container">
                <p>Hello World</p>
                //Here I want to print the values.
            </div>
        )
    }
}

export default RestGps

const totalsOrders 有请求的值,请求结构是这样的:

{
  "remissionOk": 109,
  "remissionAlert": 5,
  "remissionError": 17,
  "remissionOutOfTime": 82
}

¿ 有人可以告诉我如何在我的 html 上打印这个totalsOrders作为我的文本“Hello World”吗?问候。

标签: javascriptjavahtmlreactjsrest

解决方案


您可以使用生命周期方法。

class RestGps extends React.Component {

    state = {
      totalsOrders : null,
    };

    componentDidMount() {
      const api = restful('http://someUrl/v1/mobile', requestBackend(request));
      const totals = api.one('statusOrders',1); //organizationID = 1

    totals.get().then((response) => {
    const requestBody = response.body();
    const totalsOrders = requestBody.data(); /*Need to print this on the <div>**/
    this.setState({totalsOrders: totalsOrders });
})
    }

    render(){
        const {totalsOrders} = this.state;
        return(
             <div className="container">
                <p>Hello World</p>
            totalsOrders.map(item => {
                {item}
            }); 
            </div>
        )
    }
}

推荐阅读