为什么这个setState函数运行不正常
Why is this setState function working abnormally
我在状态中添加了一个定时器变量,每秒改变 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
你正在变异 this.state.timer
。您应该 return 下一个状态:
this.setState( prev => ({timer: prev.timer + 1}));
您看到状态递增 2
的原因是 strict mode。在严格模式下 setState
被调用两次以检测意外的副作用。更新函数应该是纯粹的(无副作用):
Strict mode can’t automatically detect side effects for you, but it
can help you spot them by making them a little more deterministic.
This is done by intentionally double-invoking the following functions:
- Class component
constructor
, render
, and shouldComponentUpdate
methods
- Class component static
getDerivedStateFromProps
method
- Function component bodies
- State updater functions (the first argument to
setState
)
- Functions passed to
useState
, useMemo
, or useReducer
我在状态中添加了一个定时器变量,每秒改变 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
你正在变异 this.state.timer
。您应该 return 下一个状态:
this.setState( prev => ({timer: prev.timer + 1}));
您看到状态递增 2
的原因是 strict mode。在严格模式下 setState
被调用两次以检测意外的副作用。更新函数应该是纯粹的(无副作用):
Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:
- Class component
constructor
,render
, andshouldComponentUpdate
methods- Class component static
getDerivedStateFromProps
method- Function component bodies
- State updater functions (the first argument to
setState
)- Functions passed to
useState
,useMemo
, oruseReducer