I am new to React and was trying a simple thing. I do not understand how to modify the state and pass it to the function. Please find my code below : I am skipping the redundant code, only passing the point of focus, everything works fine except this functionality.
state = {
card: this.props.card // No probelm here , the props are correctly received in my component
};
I am trying update the state onChange and use this state value in my dispatcher to generate a new state after this event. Please find the code snippet of this functionality here :
<select
class="form-control m-1"
value={this.state.card.type}
onChange={e => {
let newType = e.target.value;
this.setState(prevState => ({
card: {
...prevState.card,
type: newType
}
}));
console.log(this.state.card) // **This gives me the old state, not updated one**
this.props.updateCard(this.state.card) // Correctly receiving the updateCard Props ,
}}
>
<option value="ABC">Option1</option>
<option value="DEF">Option2</option>
</select>
My Dispatcher :
updateCard: card=> {
dispatch({ type: "UPDATE_CARD", card: card})}
My Reducer :
case "UPDATE_CARD": {
console.log("INSIDE REDUCER");
console.log(action.card);
return {
cards: state.cards.map(card=>
card.id === action.card.id ? action.card: card
)
};
}
Please help on this. I did search a lot of stuff here but nothing was helpful.
That's because setState
is not synchronous:
...
onChange ={e => {
let newType = e.target.value;
this.setState(prevState => ({
card: {
...prevState.card,
type: newType
}
}), () => {
console.log(this.state.card) // will give you the new value
// you should also do any updates to redux state here to trigger
// re-renders in the correct sequence and prevent race conditions
});
console.log(this.state.card) // **This gives me the old state, not updated one**
this.props.updateCard(this.state.card) // Correctly receiving the updateCard Props ,
}}
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.