React-bootstrap onSelect 方法改变状态

React-bootstrap onSelect method to change state

我有一个下拉按钮,当我 select 一个 <menuItem> 从按钮。

我正在尝试 运行 一个 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>
                   }
      },

首先你需要知道的是setState异步,这意味着当你调用setState时,它会调用挂起的状态转换并稍后更新它。

话虽如此,这意味着 console.log() 将写入 state 的旧值,即使它已更改。状态随后得到更新。 此外,我建议您在传递函数时使用 ES7 箭头语法,因此 onSelect 看起来像这样 onSelect={() => fltrPick('pentium'))} 并且功能像这样

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

(不需要这样绑定)