如果用户不采取任何措施,我需要在13分钟不活动后显示超时警告模式,并在15分钟后显示结束会话。我需要使用reactjs来实现这一点。我在https://www.npmjs.com/package/react-timeout#react-classic-verbose检查了react-timeout,但这没有用。 如果有人知道如何做到这一点,请与我分享。
答案 0 :(得分:16)
您可以像这样创建一个更高阶的组件,并可以通过更高阶的组件传递子组件
HOC:
`//代码
export default function(ComposedClass) {
class AutoLogout extends React.Component {
constructor(props) {
super(props);
this.state = {
warningTime: 1000 * 60 * 10,
signoutTime: 1000 * 60 * 15,
};
}
componentDidMount() {
this.events = [
'load',
'mousemove',
'mousedown',
'click',
'scroll',
'keypress'
];
for (var i in this.events) {
window.addEventListener(this.events[i], this.resetTimeout);
}
this.setTimeout();
}
clearTimeoutFunc = () => {
if (this.warnTimeout) clearTimeout(this.warnTimeout);
if (this.logoutTimeout) clearTimeout(this.logoutTimeout);
};
setTimeout = () => {
this.warnTimeout = setTimeout(this.warn, this.state.warningTime);
this.logoutTimeout = setTimeout(this.logout, this.state.signoutTime);
};
resetTimeout = () => {
this.clearTimeoutFunc();
this.setTimeout();
};
warn = () => {
window.alert("You will be logged out automatically in 1 minute")
console.log('You will be logged out automatically in 1 minute.');
};
logout = () => {
// Send a logout request to the API
console.log('Sending a logout request to the API...');
this.destroy();
};
destroy = () => {
//clear the session
browserHistory.push('/');
window.location.assign('/');
};
render() {
return (
<div>
<ComposedClass {...this.props} />
</div>
);
}
}
}
`
您可以将此HOC包装到路由文件中由于不活动而要向用户发出警告的所有组件
<Route path="/test" component={HOC(comonent)} />
将是您要添加此功能的页面。
答案 1 :(得分:1)
如果要通过Package实现相同的功能,则可以使用React Idle Timer Package编写以下代码
npm i react-idle-timer
import React from 'react'
import { useIdleTimer } from 'react-idle-timer'
import { useHistory } from 'react-router'
const SESSION_IDEL_MINUTES = 4;
const AutoLagoutTimer = (props: any) => {
const { ComposedClass } = props
const history = useHistory()
const handleOnIdle = (event: any) => {
// SHOW YOUR MODAL HERE AND LAGOUT
console.log('user is idle', event)
console.log('last active', getLastActiveTime())
history.push("/lagout")
}
const {getLastActiveTime } = useIdleTimer({
timeout: 1000 * 60 * SESSION_IDEL_MINUTES,
onIdle: handleOnIdle,
debounce: 500,
})
return <ComposedClass />
}
export default AutoLagoutTimer;
对于所有受保护的路线,您都可以像下面这样包装此组件
<Route path={"/dashboard"}>
<AutoLagoutTimer ComposedClass={Dashboard} />
</Route>
答案 2 :(得分:0)
这是模态怠速警告的完整示例。
假设您在此处使用reactstrap进行样式设置。
import React, {useState, useEffect} from 'react';
import {Modal, ModalHeader, ModalBody, ModalFooter} from 'reactstrap';
function IdleMonitor()
{
//Modal
const [idleModal, setIdleModal] = useState(false);
let idleTimeout = 1000 * 60 * 1; //1 minute
let idleLogout = 1000 * 60 * 2; //2 Minutes
let idleEvent;
let idleLogoutEvent;
/**
* Add any other events listeners here
*/
const events = [
'mousemove',
'click',
'keypress'
];
/**
* @method sessionTimeout
* This function is called with each event listener to set a timeout or clear a timeout.
*/
const sessionTimeout = () =>
{
if(!!idleEvent) clearTimeout(idleEvent);
if(!!idleLogoutEvent) clearTimeout(idleLogoutEvent);
idleEvent = setTimeout(() => setIdleModal(true), idleTimeout); //show session warning modal.
idleLogoutEvent = setTimeout(() => logOut, idleLogout); //Call logged out on session expire.
};
/**
* @method extendSession
* This function will extend current user session.
*/
const extendSession = () =>
{
console.log('user wants to stay logged in');
}
/**
* @method logOut
* This function will destroy current user session.
*/
const logOut = () =>
{
console.log('logging out');
}
useEffect(() =>
{
for (let e in events)
{
window.addEventListener(events[e], sessionTimeout);
}
return () =>
{
for(let e in events)
{
window.removeEventListener(events[e], sessionTimeout);
}
}
},[]);
return (
<Modal isOpen={idleModal} toggle={() => setIdleModal(false)}>
<ModalHeader toggle={() => setIdleModal(false)}>
Session expire warning
</ModalHeader>
<ModalBody>
your session will expire in {idleLogout / 60 / 1000} minutes. Do you want to extend the session?
</ModalBody>
<ModalFooter>
<button className="btn btn-info" onClick={()=> logOut()}>Logout</button>
<button className="btn btn-success" onClick={()=> extendSession()}>Extend session</button>
</ModalFooter>
</Modal>
)
}
export default IdleMonitor;
创建该类后,您可以从这样的任何地方简单地调用它
<IdleMonitor/>
不要忘记导入它。