如何编辑react中的useEffect挂钩,以便每当mySQL或数据库中有新行时,生成的表都会自动刷新



这是我的前端代码.js

import React, { useState, useEffect } from "react";
import Navbar from "../Navbar/Navbar";
import Axios from "axios"; //axios library to make requests to api
import "./Stats.css";

function Stats() {
const [customerList, setCustomerList] = useState([]); //store all that information of the database in a list
//make an axios request to get information from database
useEffect(() => {
Axios.get("http://localhost:3001/customers").then((response) => {
console.log(response.data);
setCustomerList(response.data);
});
}, []); 

{/*}
const [currentTime, setCurrentTime] = useState(1);

useEffect(() => {
fetch("/time")
.then((res) => res.json())
.then((data) => {
setCurrentTime(data.time);
});
}, []);
*/}

return (
<div>
<Navbar />
<div className="container">
<h1>Dashboard</h1>
<button>Show Dashboard</button>
</div>
<table className="customertable">
<thead>
<tr>
<th>S/N</th>
<th>Customer Name</th>
<th>Customer Email</th>
<th>Counts of Visit</th>
<th>Latest Time of Visit</th>
<th>Contacted?</th>
</tr>
</thead>
<tbody>
{customerList.map((val, key) => {
const dateStr = new Date(val.latest_time_of_visit).toLocaleDateString('en-CA');
const timeStr = new Date(val.latest_time_of_visit).toLocaleTimeString();
const dateTime = `${dateStr} ${timeStr}`;
return (
<tr>
<td>{val.ID}</td>
<td>{val.name}</td>
<td>{val.email}</td>
<td>{val.counts_of_visit}</td>
<td>{dateTime}</td>
<td>{val.contacted}</td>
</tr>
);
},)}
</tbody>
</table>
</div>
);
}
export default Stats;

我的具体问题将在react useEffect挂钩上,现在当mySQL有一行新数据时,我需要手动刷新页面,然后用新记录生成表。我如何编辑上面的代码,以便每当在mySQL中新插入一行数据时,页面都会自动刷新,从而生成表?

customerList添加到useEffect中的依赖项列表中,使useEffect中的函数在每次customerList更改时重新运行。

useEffect(() => {
Axios.get("http://localhost:3001/customers").then((response) => {
console.log(response.data);
setCustomerList(response.data);
});
}, [customerList]); 

最新更新