小编Rya*_*ark的帖子

React 中的 setTimeout 和clearTimeout

当用户使用 setTimeout 和clearTimeout 在页面上 30 秒内没有进行任何点击事件时,我正在努力创建注销功能。

但每次用户点击页面上的任何内容时,剩余时间必须再次重置为 30 秒(或者作为另一个选项,将使用clearTimeOut 和 setTimeOut。)同时,当用户没有点击页面上的任何内容时,他们通过删除 accessToken,将在 30 秒后自动注销。

所以为了解决这个问题,我的方法是这样的:

  • 当用户访问此页面时,setTimeout() 将开始。

  • 当用户单击页面上的某些内容时,clearTimeOut 将被激活,setTimeOut 也将再次被激活

  • 当用户30秒内没有点击页面上的任何内容时,他们将通过删除本地存储中的accessToken自动注销

目前,通过删除 accessToken 可以让用户在 30 秒后注销!UseEffect 中的 setTimeOut 也有效。

唯一的问题是我不知道当用户在页面上单击事件时如何使clearTimeOut()和setTimeOut工作。

import styled from 'styled-components';
import React, {useRef, useEffect, useState} from 'react';
import ScreenContainer from '../../src/component/common/ScreenContainer';
import {useNavigate as useDomNavigate} from 'react-router-dom';
import isNil from 'lodash/isNil';
import userClient from '../../src/client/user/userClient';

const Device = () => {
    const domNavigate = useDomNavigate();
    const [storeId, setStoreId] = useState(() => JSON.parse(localStorage.getItem('storeId')));
    const [currentDeposit, setCurrentDeposit] = …
Run Code Online (Sandbox Code Playgroud)

logout settimeout mouseclick-event reactjs cleartimeout

4
推荐指数
1
解决办法
7612
查看次数