如何从 API 获取用户数据以在 React 应用程序中使用



我需要你的建议!

我正在使用MongoDB在Node/Express服务器上构建一个应用程序。DB中的每个对象都有一个称为"fb_id"的唯一ID(它是一个FB信使聊天机器人(。

我编写了一个端点来检索将 id 作为 URL 参数的用户对象:

  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>

我的问题是,如何从 usersdata/:id 端点检索此用户数据以在我的 React 应用程序中使用?我想将其保存为状态对象并使用它。也许我应该在 componentDidMount 中做点什么?你能分享一下最好的方法是什么吗,谢谢。

首先,我建议你将 Express API 代码和 React Code 分成两个 apss。之后将数据提取到你的反应应用程序中,最好使用 axios( npm install axios componentDidMount() 的方法。

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

他们使用它来显示您想要的任何数据。

最新更新