clearTimeout 在 React Native 中不起作用

Mor*_*ton 5 javascript react-native

我有四个屏幕 A(主页)、B、C、D

每个屏幕都有一个功能,当屏幕onStart或时触发onResume,我通过react-redux来实现。

countdownToFirstScreen = () => {
    this.timeOut = setTimeout(()=> {
      clearTimeout(this.timeOut); // clearTimeout before navigate next screen
      this.props.leaveTheScreenTime(); // change for some redux store boolean
      this.props.navigation.navigate('A');
    }, 9000);    
  }
Run Code Online (Sandbox Code Playgroud)

如果用户<Button />在倒计时完成前点击,我也会设置 clearTimeout。

<Button 
  onPress={() => { 
    clearTimeout(this.timeOut);
    this.props.navigation.navigate('nextScreen');
  }
/>
Run Code Online (Sandbox Code Playgroud)

当我只是在 A 和 B 和 C 之间导航时它正在工作。

当我尝试从 C 导航到 D 时,会出现我的问题。

countdownToFirstScreen即使我单击C 屏上的 ,也会触发C 屏功能<Button />。

有谁知道我的setTimeout和发生了什么clearTimeout?

Hen*_*hli 10

使用React-Hooks和功能组件……事情变得容易多了……

带有empty-deps的效果[]模拟componentDidMount,并且它的cleanUp-callback模拟componentWillUnmount

  const timerRef = useRef(null);

  useEffect(() => {
    timerRef.current = setTimeout(() => {
      /** Your logic goes here */
    }, 9000);

    return () => {
      if (timerRef.current) {
        clearTimeout(timerRef.current);
      }
    };
  }, []);
Run Code Online (Sandbox Code Playgroud)


小智 6

看起来您可能会遇到范围问题,因为this在setTimeout回调中可能有不同的上下文this.timeOut,因此计时器不会被清除。理想情况下,您需要一个设置,在其中跟踪某个全局组件(例如AppComponent每个屏幕上的全局组件)中的计时器,设置如下:

componentWillMount () {
   // Add your listener
   DeviceEventEmitter.addListener('timer', this.clearTimer.bind(this));
}

componentDidMount () {
  startTimer()
}

componentWillUnMount () {
  clearTimer()
}

startTimer () {
 this.timer = this.setTimeout(() => {
   this.props.navigation.navigate('A');
 },9000);

clearTimer () {
 // Handle an undefined timer rather than null
 this.timer !== undefined ? this.clearTimeout(this.timer) : null;
}
Run Code Online (Sandbox Code Playgroud)