首页 > 解决方案 > 计数器和间隔不会停止

问题描述

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

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 
    }
  }
}

标签: react-nativeexpo

解决方案


这是对你的帮助,

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>
  )
 }
}

`


推荐阅读