【发布时间】:2021-07-23 13:47:53
【问题描述】:
我在 state 中添加了一个计时器变量,每秒改变 1 为什么它是每秒渲染 2,4,6,.. 而不是 1,2,3,.. 以及如何改进它?
import React, { Component } from 'react'
export class UseRefTimer extends Component {
interval
constructor(props) {
super(props)
this.state = {
timer:0
}
}
componentDidMount(){
this.interval = setInterval(()=>{
this.setState( prev => (this.state.timer = prev.timer + 1))
},1000)
}
componentWillUnmount(){
clearInterval(this.interval)
}
render() {
return (
<div>
Time : {this.state.timer}
</div>
)
}
}
导出默认的 UseRefTimer
【问题讨论】:
-
你真的应该使用 useEffect
-
@epascarello 你不能在类组件中使用钩子。
-
因为您正在使用
=运算符改变状态,并且您可能在严格模式下使用 React,这会导致setState回调对于每个setState调用运行两次。你需要停止改变状态。 -
@JLRishe 谢谢,并记住不要通过 = 更改状态。
标签: javascript reactjs setstate