繁体   English   中英

来自 API 的反应输出 JSON

[英]React output JSON from API

我已经设法从我创建的 api 中获取 JSON,但是我在实际呈现该 JSON 时遇到了麻烦。 我设法通过'stringify'-ing 在控制台中输出它,但是我似乎无法实际将 JSON 呈现到页面。

import React, { Component } from 'react';
import './App.css';
import $ from 'jquery';

function getData() {
  return $.ajax({
    type: "GET",
    url: 'http://localhost:3001/data',
    data: {},
    xhrFields: {
      withCredentials: false
    },
    crossDomain: true,
    dataType: 'json',
    success: handleData
  });
}
function handleData(data /* , textStatus, jqXHR */ ) {
  console.log(JSON.stringify(data));
  return JSON.stringify(data);
}

class App extends Component {
  render() {
    return (
      <div className="App">
        <header>
          <h2>Last Application Deployment </h2>
        </header>
        <div id='renderhere'>
          {JSON.stringify(getData().done(handleData))}
        </div>
      </div>
    );
  }
}

export default App;

你不能在渲染方法中执行函数作为回报。你可以使用反应生命周期并将结果存储在这样的状态 =>

class App extends Component {

      state = {result : null}          

      componentDidMount = ()=>{

        $.ajax({
           type: "GET",
           url: 'http://localhost:3001/data',
           data: {},
           xhrFields: {
             withCredentials: false
           },
           crossDomain: true,
           dataType: 'json',
           success: (result)=>{
              this.setState({result : result}); 
           }
         });

      };

      render() {
        return (
          <div className="App">
            <header>
              <h2>Last Application Deployment </h2>
            </header>
            <div id='renderhere'>
              {this.state.result && and what you want because i dont                                  know why you want use JSON.stringfy - you use .map() or ...}
            </div>
          </div>
        );
      }
    }

我建议你看看这篇文章和这个

我制作了一个演示,说明如何解决这个问题: http : //codepen.io/PiotrBerebecki/pen/amLxAw AJAX 请求不应在 render 方法中进行,而应在componentDidMount()生命周期方法中进行。 此外,最好将响应存储在状态中。 请参阅 React 文档中的指南: https : //facebook.github.io/react/tips/initial-ajax.html

在 componentDidMount 中获取数据。 当响应到达时,将数据存储在 state 中,触发渲染以更新您的 UI。

这是完整的代码:

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      time: '',
      string: ''
    };
  }

  componentDidMount() {
    $.ajax({
      type: "GET",
      url: 'http://date.jsontest.com/'
    })
      .then(response => {
        this.setState({
          time: response.time,
          string: JSON.stringify(response)
        });
    })
  }

  render() {
    return (
      <div className="App">
        <header>
          <h2>Last Application Deployment </h2>
        </header>
        <div id='renderhere'>
          Time: {this.state.time} <br /><br />
          String: {this.state.string}
        </div>
      </div>
    );
  }
}


ReactDOM.render(
  <App />,  document.getElementById('content')
);

暂无
暂无

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

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