![](/img/trans.png)
[英]How to store response data from Axios to a variable in React Functional Component?
[英]How to access data from get request made by a React functional component to localhost server using Axios?
我有一個包含客戶列表的 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 object數據,所以我知道我的查詢成功了。 但是,我無法從我的前端 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 object 數據,但我只能渲染 h1 元素。 我試圖在setCustomerList(response.data)
之后在 useEffect function 中對 customerList 進行控制台記錄,我發現它是一個空的 object。
我在這里想念什么?
您需要實際從服務器返回結果。 目前您只將它們記錄到控制台。
就像是
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);
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.