【问题标题】:issues with clear Timeout at logout注销时清除超时的问题
【发布时间】:2019-10-17 17:52:48
【问题描述】:

我有一个在登录 60 秒后显示的通知警报,问题是如果有人在这 60 秒内注销。即使用户不再登录,该消息仍会显示。

以下是我试图解决这个问题的方法,但没有成功。我需要 我已经尝试将默认导出导出为timerId,但由于 react-native 只允许一个默认导出,而这发生在这部分代码之前,我无法使用默认导出。 我尝试导出timerId;但我收到一个错误,说未解析的变量。

index.js:

_myAlert= () => {
    timerId: setTimeout(()=>{
      Alert.alert(
        'Notification',
        'Please set up your user account.'
      );
    }, 60000)
  }

抽屉.js:

onPress={() => {
             clearTimeout(this.timerId);
              this.jumpToSection('Logout');
        }
   }

【问题讨论】:

  • 这两个代码都在一个文件中吗??
  • 不,它们在两个不同的文件和目录中
  • console.log(this.timerId) 你的 timerId 正确吗?看起来您没有引用正确的计时器。您需要在某处存储对它的引用。

标签: javascript ios reactjs react-native react-native-android


【解决方案1】:

也许,您可能遇到范围问题。

下一个链接可能会有所帮助 https://cybmeta.com/var-let-y-const-en-javascript

【讨论】:

    【解决方案2】:

    这是一种解决方案,其中 timerhandle 仅在 componentWillUnmount 中清除,但仅在未按下按钮时才显示警报。

    App.js

    import React, { Component } from 'react';
    import { View, Alert } from 'react-native';
    import ClearButton from './src/ClearButton'
    
    class App extends Component {
    
        constructor(props) {
            super(props);
    
            this.timerHandle = 0;
            this.state = {
                pressed: false
            }
        }
    
        componentDidMount() {
            this.timerHandle = setTimeout(() => {
                if (!this.state.pressed) {
                    Alert.alert(
                        'Notification',
                        'Please set up your user account.'
                    );
                }
            }, 60000);
        }
    
        componentWillUnmount() {
            if (this.timerHandle) {
                clearTimeout(this.timerHandle);
            }
        }
    
        onPress() {
            this.setState({ pressed: true });
        }
    
        render() {
            return (
                <View>
                    <ClearButton onPress={this.onPress.bind(this)}/>
                </View>
            );
        }
    }
    
    export default App;
    

    ClearButton.js

    import React, { Component } from 'react';
    import { View, TouchableOpacity } from 'react-native';
    
    class ClearButton extends Component {
    
        render() {
            return (
                <TouchableOpacity onPress={this.props.onPress.bind(this)}>
                    <View style={{width: 100, height: 100, backgroundColor: '#0000ff'}}/>
                </TouchableOpacity>
            );
        }
    }
    
    export default ClearButton;
    

    如果您不想使用 this.state.pressed,我想您也可以在 App.js 的 onPress 方法中清除计时器,但您仍然不应该删除 componentWillUnmount 中的清除。

    【讨论】:

      猜你喜欢
      • 2020-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-05
      • 2021-09-26
      • 1970-01-01
      • 2011-10-23
      相关资源
      最近更新 更多