如何停止反应原生的计时器

问题描述 投票:0回答:1
import React, { Component } from 'react';
import { Text, View, TextInput, Button, Alert, Switch } from 'react-native';
import TimerMixin from 'react-timer-mixin';

export default class home extends React.Component {
  constructor(props) {
    super(props)
    this.state = { switchstate: false, timer: null };
    var timer = setInterval(this.tick, 1000);
    this.setState({ timer });
  }
  tick = async () => {
    return await console.log('asdas', 'iam printing')
  }

  toogleswitchstate = () => {
    if (this.state.switchstate == false) {
      this.setState({ switchstate: true })
    } else if (this.state.switchstate == true) {
      this.setState({ switchstate: false })
      clearInterval(this.timer);
      //geolocation.stopObserving();
    }
    console.log(this.state.switchstate)
  }

  render() {
    return (
      <View style={{ flex: 1, flexDirection: 'column', justifyContent: 'space-evenly', alignItems: 'center', backgroundColor: datum.secondaryColor }}>
        <Button
          title={String(this.state.switchstate)}
          onPress={() => this.toogleswitchstate()}
        />
      </View>
    );
  }
}

我设计此代码以在执行此组件时触发计时器,但我不知道如何停止计时器,我已经裁剪了堆栈溢出限制的代码

预期的行为:toogleswitchstate函数将停止计时器

实际发生了什么:给我一个奇怪的错误

react-native
1个回答
1
投票

这是工作代码

代码更正: -

1)setInterval是副作用,因此应该在componentDidMount中。

2)不需要在状态中填充定时器,因为它是实例变量。

3)变量名称应该像switchState一样,而不是switchstate。

4)如果尚未删除,则删除componentWillUnmount中的计时器。

import * as React from 'react';
import { Text, View, TextInput, Button, Alert, Switch } from 'react-native';
import TimerMixin from 'react-timer-mixin';

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { switchState: false };
  }
  componentDidMount(){
    this.timer = setInterval(this.tick, 5000);
  }
  tick = async () => {
   await console.log('asdas', 'iam printing');
  }
  toogleSwitchState = () => {
    clearInterval(this.timer);
    if (this.state.switchState == false) {
      this.setState({ switchState: true })
    } else {
      this.setState({ switchState: false })
      //geolocation.stopObserving();
    }
  }
  componentWillUnmount() {
    if (this.timer) clearInterval(this.timer)
  }
  render() {
    return (
      <View style={{ flex: 1, flexDirection: 'column', justifyContent: 'space-evenly', alignItems: 'center', backgroundColor: datum.secondaryColor }}>
        <Button
          title={String(this.state.switchState)}
          onPress={() => this.toogleSwitchState()}
        />
      </View>
    );
  }
}

当开关状态为真时,不确定为什么要清除定时器。如果这不是你的意图,你可以简单地写

this.setState({
    switchState: !this.state.switchState
})

切换switchState。

希望有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.