如何取消 react 中的 setTimeout 时间

How can I cancel the setTimeout time in react

我创建了一个应用程序,按下按钮时时钟开始计时。如果 23 秒后没有任何操作 (23000) 设置为 0 并且状态发生更改 (this.state.user)。这是正确的。

如果您再次点击该元素,我需要将 23 秒(23000)归零并清除超时。因为如果超时还有一些时间,项目会自动关闭。

我试过“clearTimeout (this.change); clearInterval (this.change); "可是不行,这次不知道怎么取消。

class Header extends Component {
    constructor(props) {
        super(props);

        this.change = null;

        this.state = {
            usuario: true,
            timeElapsed: 0,
            adminOrWrap: true,
        };

        ["descansoAdminWrap", "otrosDescansos",].forEach((method) => {
            this[method] = this[method].bind(this);
        });
    }

   componentDidUpdate(prevProps, prevState) {
        if (prevProps.notInCall === false && this.props.notInCall && this.state.usuario === true) {
            this.descansoAdminWrap(prevProps, prevState);
       }
   }

    descansoAdminWrap(prevProps){
        var usuarioAdminOrWrapFalse=  this.state.usuario && this.props.adminOrWrap === false;
        var notInCallFalseUsuario= this.props.notInCall === false && this.state.usuario
        //mostrar y ocultar el descanso de 'tiempo administrativo' y 'wrap time'
        if(this.state.usuario && this.props.notInCall){
            this.setState({
                usuario: false,
                timeElapsed: 0,
            });
            clearTimeout(this.change);
            clearInterval(this.change);
            if(prevProps.notInCall === false){
                this.handleAdminOrWrap(false)
                this.setState({
                    usuario: false,
                    timeElapsed: 0,
                });
                this.change = setTimeout(() => {
                    this.setState({
                        usuario: true,
                        notInCall: true,
                    });
                    this.handleAdminOrWrap(true)
                }, 23000)
            }
        }
    }

clearTimeout用于setTimeoutclearInterval用于setInterval

所以在这里使用 clearInterval 没有帮助。

我会检查您是否真的在 if 条件中使用 console.log 调用 clearTimeout,当您希望这样做时。特别是当您第一次将 state.usuario 值修改为 false 时,这将阻止您再次清除条件。