I'm attempting to update the state
of a parent component after a user changes the value of a child components select
element.
While I've got it somewhat working, I've noticed that when I fire the onChange
event on my select
element it'll return the previous value instead of the one that has just been selected.
My React Code
class Parent extends React.Component{
constructor(props){
super(props);
this.state = {
data: {
condition: "any"
}
};
}
update = data => {
this.setState({ data: { ...this.state.data, ...data } });
// this gets called every time i change the value of my select
console.log(this.state.data);
}
render(){
return (
<div className="parent">
<Child
condition={ this.state.data.condition }
onUpdate={ data => this.update(data) } />
</div>
);
}
}
class Child extends React.Component{
updateParent = data => {
this.props.onUpdate(data);
}
condition = props => {
const options = [["any", "Any Condition"], ["new", "Brand New"], ["used", "Used"]];
return (
<select
defaultValue={ props.selected }
// if i select 'used', the console will return 'any',
// then if i select 'new', the console will return 'used'
onChange={({ target }) => this.updateParent({ condition: target.value })}>
{
options.map(([id, name]) => <option key={id} value={id}>{name}</option>)
}
</select>
);
}
render(){
return (
<div className="child">
<this.condition selected={ this.props.condition } />
</div>
);
}
}
I've tried searching around, but I couldn't find any solutions to my problem (at least none that I could understand with my limited understanding). Apologies if it's glaringly obvious, but I've only just started learning React and JSX.
Cheers
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…