gpt4 book ai didi

javascript - React Hooks 功能组件的空闲超时

转载 作者:行者123 更新时间:2023-11-30 09:12:39 25 4
gpt4 key购买 nike

我有一个需要空闲超时的应用程序,它首先警告用户他们将在一分钟后注销,然后在一分钟到期后注销用户。

我已成功使用类组件,如下文所示:

Session timeout warning modal using react

我正在将我的应用程序的代码转移到 React Hooks,但我很难转移这段代码。我尝试了以下方法:

const [signoutTime, setSignoutTime] = useState(0);
let warnTimeout;
let logoutTimeout;

const setTimeout = () => {
warnTimeout = setTimeout(warn, warningTime);
logoutTimeout = setTimeout(logout, signoutTime);
};

const clearTimeout = () => {
if (warnTimeout) clearTimeout(warnTimeout);
if (logoutTimeout) clearTimeout(logoutTimeout);
};

useEffect(() => {
setWarningTime(10000);
setSignoutTime(15000);
const events = [
'load',
'mousemove',
'mousedown',
'click',
'scroll',
'keypress'
];

const resetTimeout = () => {
clearTimeout();
setTimeout();
};

for (var i in events) {
window.addEventListener(events[i], resetTimeout);
}

setTimeout();
});

const warn = () => {
console.log('Warning');
};

const destroy = () => {
console.log('Session destroyed');
};

最后,我希望出现一个模式来警告用户即将注销。如果用户移动鼠标、单击等(查看事件),则计时器会重置。如果用户单击模式中的按钮,计时器将重置。

非常感谢您的帮助!

最佳答案

试试这个

mport React, { useEffect, useState } from 'react';
const LogoutPopup = () => {
const [signoutTime, setSignoutTime] = useState(10000);
const [warningTime, setWarningTime] = useState(15000);
let warnTimeout;
let logoutTimeout;

const warn = () => {
console.log('Warning');
};
const logout = () => {
console.log('You have been loged out');
}

const destroy = () => {
console.log('Session destroyed');
}
const setTimeouts = () => {
warnTimeout = setTimeout(warn, warningTime);
logoutTimeout = setTimeout(logout, signoutTime);
};

const clearTimeouts = () => {
if (warnTimeout) clearTimeout(warnTimeout);
if (logoutTimeout) clearTimeout(logoutTimeout);
};

useEffect(() => {

const events = [
'load',
'mousemove',
'mousedown',
'click',
'scroll',
'keypress'
];

const resetTimeout = () => {
clearTimeouts();
setTimeouts();
};

for (let i in events) {
window.addEventListener(events[i], resetTimeout);
}

setTimeouts();
return () => {
for(let i in events){
window.removeEventListener(events[i], resetTimeout);
clearTimeouts();
}
}
},[]);


return <div></div>
}
export default LogoutPopup;

关于javascript - React Hooks 功能组件的空闲超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57398375/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com