检查 Reactjs 中整个组件的用户不活动情况

you*_*ds1 7 javascript reactjs

我有反应应用程序与渲染多个组件的多个路由。如何检查所有页面的用户不活动状态。如果用户在任何页面中不活动的时间超过 5 分钟,我希望执行一个执行某些操作的函数,如果用户执行一些活动,例如单击、输入等,则不活动时间应重置回 5 分钟。

研究了这些答案但无法做到。

如何优雅地检测 JavaScript 中的空闲时间?

ReactJS 如何在用户不活动时自动注销?

可以仅使用普通 Javascript 而不使用任何软件包来完成吗?

提前致谢 !

小智 12

react-idle-timer将为你完成这项工作。

你可以这样安装,

sudo npm install react-idle-timer
Run Code Online (Sandbox Code Playgroud)

或者

npm install react-idle-timer --save
Run Code Online (Sandbox Code Playgroud)

组件使用

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())
  }
}
Run Code Online (Sandbox Code Playgroud)

挂钩使用

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>
  )
}
Run Code Online (Sandbox Code Playgroud)

它们提供了很多功能,您可以在 GitHub 上的react-idle-timer上阅读这些功能