如果在单个render()
函数调用中多次调用一个函数来更改状态属性的值,则更新的值将不会在没有 prevState 机制的不同调用之间传递。
second(){
this.setState({ // no previous or latest old state passed
sec:this.state.sec + 1
}, ()=>{
console.log("Callback value", this.state.sec)
})
}
fiveSecJump(){ // all this 5 call will call together
this.second() // this call found sec = 0 then it will update sec = 0 +1
this.second() // this call found sec = 0 then it will update sec = 0 +1
this.second() // this call found sec = 0 then it will update sec = 0 +1
this.second() // this call found sec = 0 then it will update sec = 0 +1
this.second() // this call found sec = 0 then it will update sec = 0 +1
}
render() {
return (
<div>
<div> Count - {this.state.sec}</div>
<button onClick ={()=>this.fiveSecJump()}>Increment</button>
</div>
)
}
最后 sec 值将是 1,因为调用是异步的,不像 c++/c# 或 java 这样的高级编程语言总是有一个维护主线程的 main 函数。
因此,如果你想让fiveSecJump()
函数正常工作,你必须通过向它传递一个箭头函数来帮助它。上一个状态。prevState 不是关键字或成员函数,你可以在这里写任何词,如 oldState、stackTopState、lastState。它将转换为通用函数,可以完成您想要的工作。
class Counter extends Component {
constructor(props){
super(props)
this.state = {
sec:0
}
}
second(){
this.setState(prevState =>({
sec:prevState.sec + 1
}))
}
fiveSecJump(){
this.second() // this call found sec = 0 then it will update sec = 0 +1
this.second() // this call found sec = 1 then it will update sec = 1 +1
this.second() // this call found sec = 2 then it will update sec = 2 +1
this.second() // this call found sec = 3 then it will update sec = 3 +1
this.second() // this call found sec = 4 then it will update sec = 4 +1
}
render() {
return (
<div>
<div> Count - {this.state.sec}</div>
<button onClick ={()=>this.fiveSecJump()}>Increment</button>
</div>
)
}
}
export default Counter