为什么调用setState方法不立即改变状态?

为什么调用setState方法不立即改变状态?

好吧,我试着快点,因为这应该是个简单的解决办法.

我读过许多类似的问题,答案似乎很明显。从一开始我就没必要抬头看了!但是.。我有一个错误,我不知道如何修复或它发生的原因。

详情如下:

class NightlifeTypes extends Component {constructor(props) {
    super(props);

    this.state = {
        barClubLounge: false,
        seeTheTown: true,
        eventsEntertainment: true,
        familyFriendlyOnly: false
    }
    this.handleOnChange = this.handleOnChange.bind(this);}handleOnChange = (event) => {   
    if(event.target.className == "barClubLounge") {
        this.setState({barClubLounge: event.target.checked});
        console.log(event.target.checked)
        console.log(this.state.barClubLounge)
    }}render() {
    return (
        <input className="barClubLounge" type='checkbox' onChange={this.handleOnChange} checked={this.state.barClubLounge}/>
    )}

更多的代码围绕着这一点,但这正是我的问题所在。应该管用,对吧?

我也试过这样做:

handleOnChange = (event) => {   if(event.target.className == "barClubLounge") {
    this.setState({barClubLounge: !this.state.barClubLounge});
    console.log(event.target.checked)
    console.log(this.state.barClubLounge)}

所以我有那两个人console.log()两者应该是相同的。我实际上是将状态设置为与event.target.checked在上面的那条线上!

但是它总是返回它应该返回的相反的东西。

当我使用!this.state.barClubLounge如果它启动为false,则在我第一次单击时,它仍然是false,即使复选框是否选中也是基于状态的!

这是一个疯狂的悖论,我不知道发生了什么,请帮助!


红糖糍粑
浏览 1486回答 3
3回答

白衣染霜花

因为setState是一个异步函数。这意味着在调用setState之后,状态变量不会立即改变。因此,如果要在更改状态后立即执行其他操作,则应在setStateUPDATE函数中使用setstate的回调方法。handleOnChange&nbsp;=&nbsp;(event)&nbsp;=>&nbsp;{&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;inputState&nbsp;=&nbsp;event.target.checked; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if(event.target.className&nbsp;==&nbsp;"barClubLounge")&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.setState({&nbsp;barClubLounge:&nbsp;inputState},&nbsp;()&nbsp;=>&nbsp;{&nbsp;&nbsp;//here &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;console.log(this.state.barClubLounge); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//here&nbsp;you&nbsp;can&nbsp;call&nbsp;other&nbsp;functions&nbsp;which&nbsp;use&nbsp;this&nbsp;state&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;variable&nbsp;// &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;});&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;}

狐的传说

这是出于性能考虑而设计的.反应中的setState是一个函数保以重新呈现组件,这是一个昂贵的CPU进程。因此,它的设计者希望通过将多个呈现操作聚集到一个中来进行优化,因此setState是异步的。
打开App,查看更多内容
随时随地看视频慕课网APP