2017-05-11 12 views
0

これについてあなたのアドバイスが必要です!APIからユーザーデータを取得してReactアプリケーションで使用するにはどうすればいいですか?

私はMongoDBを使ってノード/エクスプレスサーバーにアプリケーションをビルドしています。 DB内のすべてのオブジェクトには "fb_id"というユニークなIDがあります(これはFBメッセンジャーチャットのボットです)。

私がURLパラメータとしてIDを持つユーザーオブジェクトを取得するためのエンドポイントを書いた:

app.get("/usersdata/:id", (req,res)=>{ 
    db.collection(USERSCOLLECTION).findOne({"fb_id": req.params.id},(err,doc)=>{ 
     if(err){ 
     handleError(res,err.message,"failed to get user data"); 
     } else{ 
     res.status(200).json(doc); 
     } 
    }); 
    }); 

I am using React in the front-end and D3, planning to build a personal dashboard for every user. Here is my starting code: 

/*global React*/ 
/*global ReactBootstrap*/ 
/*global ReactDOM*/ 

alert("hello world"); 

const App = React.createClass({ 
//parent component to render all elements and hold state 
    getInititialState(){ 
     return{ 

     }; 
    }, 

    componentDidMount: function(){ 


    }, 

    render: function(){ 

     return (
      <div className="container"> 
       <h1>Chart Here</h1> 
       <p>Hello</p> 
      </div> 
     ); 

    } 

});//App component 

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

そして、私のHTML:

<html> 
<head> 
    <meta charset="utf-8"> 
    <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.min.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.min.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script> 
    <!--Load React and D3 script here-->  
    <script type="text/babel" src="/js/dashboard.js"></script> 
    <!--link custom css file--> 
    <link rel="stylesheet" type="text/css" href="/css/style.css"> 
</head> 
<body> 
    <div class="container"> 
     <h1>My Dashboard</h1> 
     <!--Initialise React app here--> 
     <div id="app"> 
     </div> 
    </div> 
</body> 

私の質問はどのように私はできていますこのユーザーデータを私のReact Appで使用するusersdata /:idエンドポイントから取得しますか?私はそれに状態オブジェクトを保存し、それを使用したいと思います。多分私はcomponentDidMountで何かすべきでしょうか?あなたはこれについて最善のアプローチを共有することができますpls、ありがとう。

+1

あなたはクライアントサイドコードを試しましたか? –

+0

私はcomponentDidMount()でフェッチを試みましたが、まだわからない:URLからIDを取得する – chemook78

答えて

1

まず、Express APIコードとReact Codeを2つのapsに分けることをお勧めします。その後、反応アプリケーションにデータを取得するには、componentDidMount()メソッドをaxios(npm install axios)を使用して使用する方が良いです。

componentDidMount(){ 
     axios.get('localhost_url/usersdata/:id') 
     .then(response => { 
      this.setState({ message_user : response.data }) 
     }) 
    } 

そして、それらを使用して任意のデータを表示できます。

+0

ありがとう、私は同じことをやったが、最終的にはフェッチを使った – chemook78

関連する問題