计数器和间隔不会停止

时间:2019-10-13 19:59:12

标签: react-native expo

我是本机的新手,当计数器变为9时,我想通过(componentWillUnmount()函数和“ show”)停止计数器并停止间隔,但是计数器和间隔不会停止,并且在那里没有错误,那么问题出在哪里?

class Counter extends Component {
  constructor(){
    super()
    this.state = {
      count : 0,
      show : true
    }
  }
  componentDidMount() {
    this.interval = setInterval(this.incrementCount, 1000)
  }
  componentWillUnmount(){
    clearInterval(this.interval)
  }
  toggleCounter = () => this.setState(prevState => ({
    show : !prevState.show,
  }))
  incrementCount = () => {
      console.log("inc")
      this.setState(prevState => ({count: prevState.count + 1}))
  }

  render() {
  if (this.state.count > 9 ){
    console.log("the if statement")
    this.toggleCounter
  }

    if(this.state.show)
    {
      return (<Text style ={styles.text}>{this.state.count}</Text>);
    }else{
      return null 
    }
  }
}

1 个答案:

答案 0 :(得分:0)

这对您有帮助

import React, { Component } from 'react'
import { Text, View } from 'react-native' 

export default class App extends Component {
state={
 count:0
}
componentDidMount(){
let count=setInterval( () => { 
  if(this.state.count<=9){
  this.setState({
    count:this.state.count+1
  })
 }
 else{
  clearInterval(count)
 }
 }, 1000);

 }


render() {
return (
  <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
    <Text> {this.state.count} </Text>
  </View>
  )
 }
}

`