我有几个路由渲染几个组件的 react 应用程序。我如何检查所有页面的用户不活动状态。如果用户在任何页面中处于非事件状态超过 5 分钟,我希望执行一个执行某些操作的函数,如果用户执行一些事件,如单击、输入等,则不活动时间应重置回 5 分钟。
调查了这些答案,但无法做到。
How to detect idle time in JavaScript elegantly?
How to auto log off when a user is inactive in ReactJS?
可以只使用没有任何软件包的 Vanilla Javascript 来完成吗?
提前致谢 !
最佳答案
包react-idle-timer将为您完成工作。
可以这样安装
sudo npm install react-idle-timer
或者npm install react-idle-timer --save
组件使用import React, { Component } from 'react'
import IdleTimer from 'react-idle-timer'
export default class YourApp extends Component {
constructor(props) {
super(props)
this.idleTimer = null
this.handleOnAction = this.handleOnAction.bind(this)
this.handleOnActive = this.handleOnActive.bind(this)
this.handleOnIdle = this.handleOnIdle.bind(this)
}
render() {
return (
<div>
<IdleTimer
ref={ref => { this.idleTimer = ref }}
timeout={1000 * 60 * 15}
onActive={this.handleOnActive}
onIdle={this.handleOnIdle}
onAction={this.handleOnAction}
debounce={250}
/>
{/** Your app/component here. */}
</div>
)
}
handleOnAction (event) {
console.log('user did something', event)
}
handleOnActive (event) {
console.log('user is active', event)
console.log('time remaining', this.idleTimer.getRemainingTime())
}
handleOnIdle (event) {
console.log('user is idle', event)
console.log('last active', this.idleTimer.getLastActiveTime())
}
}
钩子(Hook)用法import React from 'react'
import { useIdleTimer } from 'react-idle-timer'
import App from './App'
export default function (props) {
const handleOnIdle = event => {
console.log('user is idle', event)
console.log('last active', getLastActiveTime())
}
const handleOnActive = event => {
console.log('user is active', event)
console.log('time remaining', getRemainingTime())
}
const handleOnAction = event => {
console.log('user did something', event)
}
const { getRemainingTime, getLastActiveTime } = useIdleTimer({
timeout: 1000 * 60 * 15,
onIdle: handleOnIdle,
onActive: handleOnActive,
onAction: handleOnAction,
debounce: 500
})
return (
<div>
{/** Your app/component here. */}
</div>
)
}
它们提供了许多功能,您可以在 GitHub 上的 react-idle-timer 上阅读这些功能。
关于javascript - 在 Reactjs 中检查整个组件中的用户不活动状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67520897/