React 中的 setState 未提供所需的输出
setState in React not giving desired output
下面是我的代码。它给我的结果是 0, 1,2 , 4, 8, 16.... 这有什么问题。我是新反应。
从 'react'
导入 {react,Component}
class Timer extends Component{
constructor(props){
super(props);
this.state={
count:0
}
}
updateTime(){
setInterval(() => {
var number=this.state.count+1;
this.setState({ count:number })} , 5000);
}
render(){
this.updateTime()
return(
<div>
<h1>{this.state.count}</h1>
</div>
)
}
}
export default Timer;
但是如下更改 updateTime 函数,给出了预期的结果
updateTime(){
var number=this.state.count;
setInterval(() => {
number++;
this.setState({ count:number })}, 5000);
}
预期结果:- 每 5 秒将数字递增 1
每次渲染时,您都会调用 updateTime()
,这会启动一个新的计时器。
仅在 componentDidMount
中调用 updateTime()
而不是在 render
中调用。
确保在卸载时清除计时器:
componentDidMount() {
this.timer = this.updateTime();
}
componentWillUnmount() {
clearInterval(this.timer);
}
updateTime(){
return setInterval(() => {
var number=this.state.count+1;
this.setState({ count:number })
}, 5000);
}
每次状态更新时,render()
函数都会运行。每次 render()
运行时,您都在调用 this.updateTime()
,这是多次设置间隔。在 4 次渲染调用之后,您有 4 个计时器在运行,每个计时器每次都会将 state.count
递增 1。减少间隔数,设置一次间隔即可:
componentDidMount() {
this.updateTime();
}
下面是我的代码。它给我的结果是 0, 1,2 , 4, 8, 16.... 这有什么问题。我是新反应。 从 'react'
导入 {react,Component}class Timer extends Component{
constructor(props){
super(props);
this.state={
count:0
}
}
updateTime(){
setInterval(() => {
var number=this.state.count+1;
this.setState({ count:number })} , 5000);
}
render(){
this.updateTime()
return(
<div>
<h1>{this.state.count}</h1>
</div>
)
}
}
export default Timer;
但是如下更改 updateTime 函数,给出了预期的结果
updateTime(){
var number=this.state.count;
setInterval(() => {
number++;
this.setState({ count:number })}, 5000);
}
预期结果:- 每 5 秒将数字递增 1
每次渲染时,您都会调用 updateTime()
,这会启动一个新的计时器。
仅在 componentDidMount
中调用 updateTime()
而不是在 render
中调用。
确保在卸载时清除计时器:
componentDidMount() {
this.timer = this.updateTime();
}
componentWillUnmount() {
clearInterval(this.timer);
}
updateTime(){
return setInterval(() => {
var number=this.state.count+1;
this.setState({ count:number })
}, 5000);
}
每次状态更新时,render()
函数都会运行。每次 render()
运行时,您都在调用 this.updateTime()
,这是多次设置间隔。在 4 次渲染调用之后,您有 4 个计时器在运行,每个计时器每次都会将 state.count
递增 1。减少间隔数,设置一次间隔即可:
componentDidMount() {
this.updateTime();
}