尝试通过 Axios 从 Get 请求中打印数据

Trying to Print Data from Get Request via Axios

我正在尝试使用 axios 从 get 请求中打印出 SQL 数据。我正在使用 express 服务器端,我的前端是 React。在我的反应组件中,我有一个具有 axios GET 调用的函数,然后我在渲染中调用该函数。我可以很好地获取数据。我的问题实际上是将数据打印到 table。到目前为止,这是我的代码:

  getTableData(){
      axios.get("/api")
      .then(function (response){
        return(
          Object.keys(response).map( (row, index) => (
              <TableRow key={index} selected="false">
                <TableRowColumn>Test</TableRowColumn>
                <TableRowColumn>Test</TableRowColumn>
              </TableRow>
          ))
        )
      })
      .catch(function (error){
          console.log(error);
      })
  }

这是我用来执行 API 调用以及尝试打印 table 的函数。我在渲染函数中将其称为 {this.getTabledata()}.

这是我的 server.js:

中的获取请求
app.get('/api', function (req, res){
    sql.connect(config, err =>{
        new sql.Request().query('select * from Counselling', (err, result) =>{
            var table = new Object();
            result["recordset"].map( (row, index) => (
                table[row["StudentName"]] = row["StudentNumber"]
            ));
            res.send(table);
            sql.close();
        });
    });

有什么我想念的吗?我必须对行使用特定的映射函数吗?

首先,不要直接从 render 方法生成 api call,而是在 componentDidMount 生命周期方法或任何特定的 event 中进行。将响应存储在 state 变量中,因为 api 调用将是异步调用,它不会 return ui 元素。

使用它从服务器获取数据:

componentDidMount(){
    axios.get("/api")
        .then( (response) => {
            this.setState({response: response})
        })
        .catch( (error) => {
            console.log(error);
        })
}

使用此方法,一旦您从服务器获得响应,它将 return Table 行,因为当我们再次执行 setStateReact render 组件时。

getTableData(){

    if(!this.state.response) return null;  //added this line

    return Object.keys(this.state.response).map( (row, index) => (
         <TableRow key={index} selected="false">
             <TableRowColumn>Test</TableRowColumn>
             <TableRowColumn>Test</TableRowColumn>
         </TableRow>
    ))     
}