react-native - 计数器和间隔不会停止
问题描述
我是本机反应的新手,我想在计数器变为 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
}
}
}
解决方案
这是对你的帮助,
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>
)
}
}
`
推荐阅读
- python - 我无法调试此代码,不确定我缺少什么逻辑
- c - 危险类型转换的 C 编译器警告
- javascript - 用js移动svg多边形时闪烁
- android - TextField 隐藏在键盘后面 - Jetpack Compose
- adobe - Adobe flex:如何访问被系统用户帐户 ID 锁定的文件?
- python - 按多列对 Pandas Dataframe 进行分组以获得特定值
- javascript - 如何在 Laravel 中创建动态依赖下拉菜单?
- javascript - JavaScirpt - window.console 代理
- python - 为什么这个自动点击器程序在开始点击时会停止?
- html - 中间有边框、背景图像和徽标的框