相关疑难解决方法(0)

为什么调用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}/>
    )
}
Run Code Online (Sandbox Code Playgroud)

更多代码围绕着这个,但这就是我的问题所在.应该工作吧?

我也试过这个:

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

所以我有两个console.log(),都应该是一样的.我确实将状态设置为与event.target.checked它上面的行相同!

但它总是与它应该的相反.

我使用时也一样!this.state.barClubLounge; 如果它开始为假,在我第一次点击它仍然是假的,即使复选框是否被选中是基于状态!!

这是一个疯狂的悖论,我不知道最新情况,请帮忙!

html javascript event-handling reactjs

42
推荐指数
1
解决办法
6112
查看次数

标签 统计

event-handling ×1

html ×1

javascript ×1

reactjs ×1