17

如果用户不采取任何行动,我需要在 13 分钟不活动后显示超时警告模式,并在 15 分钟后结束会话。我需要使用 reactjs 来实现这一点。我在https://www.npmjs.com/package/react-timeout#react-classic-verbose检查了反应超时,但这没有帮助。如果有人知道这样做的方法,请与我分享。

4

3 回答 3

23

您可以像这样创建一个高阶组件,并且可以通过高阶组件传递子组件

特设:

`// 代码

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)} />

在上面的代码组件中将是您要添加此功能的页面。

于 2017-11-13T18:12:00.230 回答
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>
于 2020-08-14T21:24:38.920 回答
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/>

不要忘记导入它。

于 2020-08-25T22:08:23.300 回答