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.info('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.info(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 остановит таймер
Что произошло на самом деле: Выдает мне странную ошибку





Это рабочий код
Исправление в коде: -
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.info('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
})
для переключения состояния переключения.
Надеюсь, это поможет!!!
Я думаю, вам также нужно изменить состояние после интервала очистки, this.setState({timer:null})