英文:
Handle Browser beforeunload with react-router-dom v6 page navigation
问题
我有一个使用react-router
v6构建的简单应用程序,我的用例是在页面卸载时使用最后更新的状态调用API。
const handleBeforeUnload = () => {
console.log("Running unload");
};
React.useEffect(() => {
window.addEventListener("beforeunload", handleBeforeUnload);
return () => window.removeEventListener("beforeunload", handleBeforeUnload);
}, []);
在上述代码中,当我重新加载浏览器时,处理程序被调用。但是,当我尝试通过具有NavLink
的侧边栏导航时,卸载不会被调用,因为react-router-dom
执行客户端端路由,因此页面实际上从未被卸载。那么,如何在react-router-dom
导航时在页面卸载时运行这段代码?
示例代码:https://codesandbox.io/s/lingering-pond-gt5u6d
英文:
I have a simple application with the navigation built with react-router
v6. My use case is to call an API with the last updated state on page unload.
const handleBeforeUnload = () => {
console.log("Running unload");
};
React.useEffect(() => {
window.addEventListener("beforeunload", handleBeforeUnload);
return () => window.removeEventListener("beforeunload", handleBeforeUnload);
}, []);
With the above code when I reload the browser the handler is getting called. But when I'm trying to navigate via sidebar having NavLink
, the unload is not getting called because react-router-dom
do client side routing so page is not actually never getting unload. So How can I run the piece of code on page unload with react-router-dom
Navigation?
Sample Code:- https://codesandbox.io/s/lingering-pond-gt5u6d
答案1
得分: 0
以下是已翻译的内容:
You'll need to handle all the different ways a user leaves the component differently. Use beforeunload
when the page is reloaded or closed, use an effect cleanup function to handle when the component is just unmounted.
Example:
React.useEffect(() => {
const handleBeforeUnload = () => {
console.log("Running unload");
};
// handles when page is unloaded
window.addEventListener("beforeunload", handleBeforeUnload);
// cleanup function handles when component unmounts
return () => {
window.removeEventListener("beforeunload", handleBeforeUnload);
handleBeforeUnload();
};
}, []);
英文:
You'll need to handle all the different ways a user leaves the component differently. Use beforeunload
when the page is reloaded or closed, use an effect cleanup function to handle when the component is just unmounted.
Example:
React.useEffect(() => {
const handleBeforeUnload = () => {
console.log("Running unload");
};
// handles when page is unloaded
window.addEventListener("beforeunload", handleBeforeUnload);
// cleanup function handles when component unmounts
return () => {
window.removeEventListener("beforeunload", handleBeforeUnload);
handleBeforeUnload();
};
}, []);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论