我发现这条评论与我所寻找的内容相匹配。对我来说,它似乎与“console.log”完美地结合在一起。我想知道用户何时离开页面:
const getChatRoomId = () => {}
useEffect(() => {
const chatRoomId = getChatRoomId()
if (chatRoomId) {
console.log('----HAS ENTERED /messages/* ------', chatRoomId)
}
// I believe this is not important?
const routeChangeStart = url => {}
// This is very important
const beforeunload = e => {
if (chatRoomId) {
console.log(`---- IS LEAVING /messages/${chatRoomId} ------`)
}
}
window.addEventListener('beforeunload', beforeunload);
Router.events.on('routeChangeStart', routeChangeStart);
return () => {
window.removeEventListener('beforeunload', beforeunload);
Router.events.off('routeChangeStart', routeChangeStart);
};
}, [someStateChangeVariable])
上面的代码很好用,但是在beforeunload
中使用一个函数就不行了。我做了一些搜索,其中一个声明是“return a string“:
[..]
// This is very important
const beforeunload = e => {
if (chatRoomId) {
alert(`---- IS LEAVING /messages/${chatRoomId} ------`)
}
return 'GoodBye!'
}
[..]
在卸载之前阻止警报('---- IS LEAVING /messages/1 ------')。
我使用NextJs catch all route /pages/[...messages]
,你可以有一个页面id为“new”或“123”,其中“123”是消息id,“new”创建一个新消息.如何在用户离开页面时触发一个函数?
1条答案
按热度按时间fzsnzjdm1#
您可以使用router.events方法. Mextjs docs
this topic也可能相关