2016-10-03 76 views
1

我已經設法從我創建的api獲取JSON,但是我實際上在渲染該JSON時遇到了麻煩。我已經設法通過'stringify'輸出它在控制檯中,但我似乎無法實際呈現JSON到頁面。從API反應輸出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; 

回答

1

你不能執行一個功能在渲染方法return.you可以使用生命週期的反應,結果存儲狀態是這樣=>

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

我建議你看this文章和this

0

我已經演示瞭如何解決這個問題:http://codepen.io/PiotrBerebecki/pen/amLxAw。 AJAX請求不應該在渲染方法中進行,而應該在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') 
);