我正在尝试使用 axios 打印来自 get 请求的 SQL 数据。我使用的是 Express 服务器端,我的前端是 React。在我的 React 组件中,我有一个具有 axios GET 调用的函数,然后我在渲染中调用该函数。我可以很好地获取数据。我的问题实际上是将数据打印到表中。这是到目前为止我的代码:
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 调用以及尝试打印表格的函数。我在渲染函数中将其称为 {this.getTabledata()}。
这是我的 server.js 中的 get 请求:
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 调用
,可以在 componentDidMount
生命周期方法或任何特定的方法中执行此操作事件
。将响应存储在 state
变量中,因为 api 调用将是异步调用,它不会返回
ui 元素。
使用它从服务器获取数据:
componentDidMount(){
axios.get("/api")
.then( (response) => {
this.setState({response: response})
})
.catch( (error) => {
console.log(error);
})
}
使用此方法,一旦收到服务器的响应,它将返回
表格行,因为当我们执行setState
时,React 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>
))
}
关于javascript - 尝试通过 Axios 打印 Get 请求中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43258931/