我试图在用户处于非活动状态大约 10 秒后创建自动注销,但它不起作用。它不会在指定时间后注销用户。
const Layout = () => {
let timer;
useEffect(() => {
Object.values(events).forEach((item) => {
window.addEventListener(item, () => {
resetTimer();
handleLogoutTimer();
});
});
}, [])
const events = [
"load",
"mousemove",
"mousedown",
"click",
"scroll",
"keypress",
];
const handleLogoutTimer = () => {
timer = setTimeout(() => {
// clears any pending timer.
resetTimer();
// Listener clean up. Removes the existing event listener from the window
Object.values(events).forEach((item) => {
window.removeEventListener(item, resetTimer);
});
// logs out user
navLogout()
}, 10000); // 10000ms = 10secs. You can change the time.
};
// this resets the timer if it exists.
const resetTimer = () => {
if (timer) clearTimeout(timer);
};
return (
<div >
<Row>
<Col lg={5} className=''>
<Aside />
</Col>
<Col xl={19} lg={19} md={19} sm={24} xs={24}>
<Row>
<Col span={24}>
<Navbar />
</Col>
<Col span={24}>
<div className="outlet">
<Outlet />
</div>
</Col>
</Row>
</Col>
</Row>
</div>
)
}
export default Layout
据我所知,您没有使用 useeffect 的清理功能,而是在函数调用本身中进行清理,您需要将它们分开。您可以查看这个答案Handle User Inactivity and Logout in React