2017-07-24 35 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

相应地更新了答案,我忘了将函数重写为箭头语法。 –