我的数据库中有每隔几秒更新一次的数据表。 我想实时显示它们 - 当数据库中有更新时, 反应中显示的信息将是 自动更新,无需刷新页面。 例如-
useEffect(() => {
const apiUrl = 'http://localhost:3001/main-table/receptionQueue';
axios.get(apiUrl)
.then(response => {
setQueue(response.data);
})
.catch(error => {
console.error('Error fetching reception queue data:', error);
});
}, []);
当我运行上面的代码时 - 这是一个 get 请求。 当我删除方括号时,会出现很多没有中断的获取请求 - 这会导致速度缓慢和资源消耗高。 有谁知道如何编写它,只有当数据库中有更新时, get请求将在客户端执行? 任何解决方案都会真正帮助我! 谢谢:)
我尝试制作一个 webSocket 但它有点复杂......
1.使用useState(): 2. 你想什么时候获取新数据?每隔几秒钟?如果是这样,请将其全部放入计时器中
const [data, setData] = useState();
useEffect(() => {
const apiUrl = "http://localhost:3001/main-table/receptionQueue";
const interval = setInterval(function () {
axios
.get(apiUrl)
.then((response) => {
setData(response.data);
})
.catch((error) => {
console.error("Error fetching reception queue data:", error);
});
}, 5000);
return () => {
clearInterval(interval);
};
}, []);