如何在页面重载或关闭之前使用ReactJS发送API调用
要在页面重载或关闭之前使用React JS发送API调用,我们必须在页面卸载时链接或定义一个函数。页面卸载发生在页面关闭或尝试重新加载之前。
先决条件
- React JS
- HTML DOM onbeforeinload事件
方法
我们将使用一些监听器,如 “beforeupload” 和 “upload” ,触发发送API调用的函数。该监听器仅在页面重载或关闭之前才会触发函数,以便我们从API获取更新后的结果。
创建React应用程序
步骤1: 在终端中使用此命令启动一个React项目。
npx create-react-app <folder-name>
步骤2: 移动到项目目录
cd <folder-name>
项目结构
项目的结构看起来将会像这样。
示例:
示例演示了在页面重新加载之前使用beforeunload事件监听器发送API调用。
import { useState, useEffect } from "react";
function App() {
const [data, setData] = useState("Loading...");
const getData = () => {
fetch("https://api.adviceslip.com/advice")
.then((response) => response.json())
.then((data) => {
setData(data.slip.advice);
});
}
useEffect(() => {
getData();
}, []);
window.addEventListener("beforeunload", (event) => {
getData();
console.log("API call before page reload");
});
window.addEventListener("unload", (event) => {
getData();
console.log("API call after page reload");
});
return (
<div>
<h1>GeeksforGeeks</h1>
<h3>{data}</h3>
</div>
);
}
export default App;
运行应用程序的步骤: 将此命令在项目目录中终端使用。
npm start
输出: 此输出将在浏览器窗口上可见 http://localhost:3000/ 。