亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么調用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 關注
  • 1556 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號