问题描述
我有一个包含客户列表的 MysqL 数据库。我可以使用以下代码通过 Express 从服务器端访问此列表:
app.get("/customer/lookup",(req,res) => {
const sqlSelect =
"SELECT * FROM customers;";
db.query(sqlSelect,(err,result) => {
if (!err) {
console.log(result);
} else {
console.log(err);
}
});
});
我可以看到终端中显示的 JS 对象数据,所以我知道我的查询成功了。但是,我无法从前端 React 组件成功发出 GET 请求。这是我正在使用的代码:
import React,{useState,useEffect} from "react";
import axios from "axios";
import { Link,Switch,Route } from 'react-router-dom';
function LookupTable() {
const [customerList,setCustomerList] = useState([]);
useEffect(()=> {
axios.get("http://localhost:4000/customer/lookup")
.then(response => {
setCustomerList(response.data)
});
},[]);
return (
<div>
<h1>Lookup Table</h1>
{customerList.map((val)=> {
return <p>Customer: {val.fullName}</p>
})}
</div>
);
}
export default LookupTable;
我现在只是尝试在浏览器中呈现相同的 JS 对象数据,但我只能呈现 h1 元素。我试图在 setCustomerList(response.data)
之后的 useEffect 函数中控制台记录 customerList,我看到它是一个空对象。
我在这里遗漏了什么?
解决方法
您需要从服务器实际返回结果。目前,您只将它们记录到控制台。
类似的东西
app.get("/customer/lookup",(req,res,next) => {
const sqlSelect = "SELECT * FROM customers;";
db.query(sqlSelect,(err,result) => {
if (!err) {
console.log(result);
res.json(result);
} else {
console.log(err);
next(err);
}
});
});