אלעד בן אדרת אלעד בן אדרת - 3 years ago 187
React JSX Question

React-bootstrap onSelect method to change state

i have a dropdown button, when i select a

<menuItem>
from the button.

im trying to run a function that
setState({fltrName:"pentium})
.

the thing is that it doesent work the function will run and it
console.log()
,
but it doesnt change the state and why is that ?
here is the function

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>
}
},

Answer Source

First thing you need to know is that setState is asynchronous, which means that when you call setState, it calls pending state transition and updates it later.

That being said, it means that console.log() will write old value of state even though it changed. State gets updated afterwards. Also, I would advise you to use ES7 arrow syntax when passing functions, so onSelect would look like this onSelect={() => fltrPick('pentium'))} and function like this

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

(you don't need to bind it this way).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download