2017-07-24 71 views
0

我有一個下拉按鈕,當我從按鈕中選擇一個<menuItem>React-bootstrap onSelect方法改變狀態

即時通訊設法運行一個功能,setState({fltrName:"pentium})

事情是,它沒有工作的功能將運行,它console.log(), 但它並沒有改變狀態,爲什麼? 這裏是功能

 fltrFunc:function(name){ 

     function fltrPick(pick){   
     this.setState({fltrName:pick}) // sholud set to "pentium" 
     console.log(this.state.fltrName) //but console "proccessor" (dosent change) 
     } 

     switch(name){ 
      case "processors": 
      return (
       <DropdownButton id="dropdownBtn" bsSize="xsmall" title={name} > 
       <MenuItem eventKey="1" onSelect={fltrPick.bind(this,"pentium")} >pentium </MenuItem> 

      // above should run the func fltrPick() and change the state 

       <MenuItem eventKey="2">i3</MenuItem> 
       <MenuItem eventKey="3">i7</MenuItem> 
       </DropdownButton> 
        ) 
      braek; 
      default: return <DropdownButton title="nothing for now"> </DropdownButton> 
        } 
     }, 

回答

1

你需要知道的第一件事是,setState異步,這意味着當你調用的setState,它調用掛起狀態過渡,以後更新它。

這就是說,這意味着console.log()將寫入舊值state,即使它已更改。狀態在事後得到更新。 另外,我勸你傳遞函數時使用ES7箭頭語法,所以ONSELECT看起來像這樣onSelect={() => fltrPick('pentium'))}和功能類似這樣

fltrPick = (pick) => { 
    this.setState({fltrName:pick})  
} 

(你不需要這樣其綁定)。

+0

現在的事情是,它給了我一個錯誤「無法讀取未定義的屬性'setState'」爲什麼它未定義什麼不綁定在這裏? –

+0

相應地更新了答案,我忘了將函數重寫爲箭頭語法。 –