2016-10-03 4 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方法をレンダリングで関数を実行カントは、私はあなたがthis記事と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> 
     ); 
     } 
    } 

のような状態にライフサイクルとストア結果を反応させます。

0

私はあなたがこれを解決する方法のデモを行った:http://codepen.io/PiotrBerebecki/pen/amLxAw。 AJAXリクエストは、レンダリングメソッドではなく、componentDidMount()ライフサイクルメソッドで行う必要があります。また、レスポンスを状態で保存するのが最善です。 React docsのガイダンスを参照してください。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') 
); 
関連する問題