如何在用户在ReactJS中处于非活动状态时自动注销?
问题描述:
我需要知道是否有REACT JS或HTML5中的任何API,当用户处于非活动状态时,它提供了auto-log关闭的功能。我的代码在下面我不知道什么是错误它给我的错误startTimer不是定义和不必要的binding.Please告诉我,我错了如何在用户在ReactJS中处于非活动状态时自动注销?
import React from 'react';
import ReactDOM from 'react-dom';
import './App.css';
class Toogle extends React.Component {
constructor(props) {
super(props);
//step 1
this.handleClick = this.handleClick.bind(this);
this.startTimer=this.startTimer.bind(this)
}
handleClick() {
console.log('Button is clicked');
// clearTimeout(timeoutTimer);
startTimer() {
var timeoutTimer = setTimeout(function() {
window.location.href = '#/security/logout';
}.bind(this), 1000);
}
}
render() {
return (<div onMouseMove={this.handleClick}>Move the cursor over me</div>);
}
}
ReactDOM.render(
<Toogle />,
document.getElementById('root')
);
答
如果您使用的是react-router
库添加前端路由的配置,只要用户导航到另一个页面,您可以触发一个功能。
<Route path="/" onEnter={onUserNavigate} onChange={onUserNavigate}>
...
</Route>
然后,您可以让您的事件处理函数计算用户导航之间的时间。
N.B.这仅仅是一个框架代码(作为原型为您的实际方法)
function onUserNavigate() {
let idleTime = getCurrentTime() - getPreviousNavTime();
storeCurrentNavTime();
if (idleTime > ALLOWED_IDLE_TIME)
window.location.href = '#/security/logout';
}
因此,上述功能假定,
- 你有一个方法来获得当前时间(
getCurrentTime
功能) - 你必须存储和获取时间戳当用户导航到一个页面
- 你有一个恒定叫
ALLOWED_IDLE_TIME
存储允许的空闲时间的用户两页之间花费最小的方法。 - 您有一个注销URL(在上面的示例代码中,值为
#/security/logout
) - 用户不需要在浏览反应路由器路径时与页面交互。例如,用户可以使用超出允许的空闲时间的浏览器控制台与页面进行交互。
对于timestamp相关的计算和方法,你可以使用任何JavaScript库,例如momentjs
希望这有助于。
UPDATE零件周围存在不必要的绑定}.bind(this), 1000);
只需删除.bind(this)
段。
另外,startTimer() {
片段应该会给你语法错误。为此,你应该删除startTimer() {
线和其相应的关闭}
线
非常广泛的问题..不是真的太值得。您必须自己编写这些功能或查找认证软件包。 –