从API响应输出JSON

我已经成功地从我创build的api获取JSON,但是我实际上正在渲染那个JSON。 我已经设法通过'stringify'它在控制台输出它,但我似乎无法实际呈现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; 

你不能在渲染方法中执行一个函数,你可以使用反应生命周期并把结果存储在这个状态,就像this =>

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

我build议你看看这篇文章和这个 。

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

在componentDidMount中获取数据。 当响应到达时,将数据存储在状态中,触发渲染来更新您的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') );