为了账号安全,请及时绑定邮箱和手机立即绑定

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

为什么调用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,即使复选框是否选中也是基于状态的!这是一个疯狂的悖论,我不知道发生了什么,请帮助!
查看完整描述

3 回答

?
白衣染霜花

TA贡献1796条经验 获得超10个赞

因为setState是一个异步函数。这意味着在调用setState之后,状态变量不会立即改变。因此,如果要在更改状态后立即执行其他操作,则应在setStateUPDATE函数中使用setstate的回调方法。

handleOnChange = (event) => { 
     let inputState = event.target.checked;
      if(event.target.className == "barClubLounge") {
         this.setState({ barClubLounge: inputState}, () => {  //here
             console.log(this.state.barClubLounge);
             //here you can call other functions which use this state 
             variable //
         });        
      }
   }


查看完整回答
反对 回复 2019-06-05
?
狐的传说

TA贡献1804条经验 获得超3个赞

这是出于性能考虑而设计的.反应中的setState是一个函数以重新呈现组件,这是一个昂贵的CPU进程。因此,它的设计者希望通过将多个呈现操作聚集到一个中来进行优化,因此setState是异步的。


查看完整回答
反对 回复 2019-06-05
  • 3 回答
  • 0 关注
  • 1480 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信