I am fairly new to React.js and just ran into a problem when trying to validate a form. I have the following form field and onChange function:
<AvField type="text" name="name" id="name" placeholder="Name" value={scheduleEvent.name} onChange={this.inputChange} className="form-control-sm" required />
inputChange = (event) => {
const { name, value } = event.target;
console.log(name, value);
let scheduleEvent = {...this.state.scheduleEvent};
console.log(scheduleEvent);
scheduleEvent[name] = value;
console.log(scheduleEvent);
this.setState({scheduleEvent});
console.log(this.state.scheduleEvent);
}
When I type in "a", I get the following console.log outputs:
name a //as expected
{name: ""} //as expected
{name: "a"} //as expected
{name: ""} //this.state.scheduleEvent did not get updated
Then, if I type in another character, console.log outputs are as follows:
name aa //as expected
{name: "a"} //as expected, but for whatever reason it did not get updated on the first invocation of inputChange
{name: "aa"} //as expected
{name: "a"} // did not get updated
When I submit the form, however, this.state.scheduleEvent is correct.
I also tried this example linked from the React website: https://codepen.io/gaearon/pen/VmmPgp?editors=0010 The same issue exists there as well. Is there anyway to fix this?
Thanks
Beware setState is asynchronous! State updates are sent to a queue that will be pending until processed, therefore there will be a possibility that you will be returned the existing state. To guarantee that we will ALWAYS access the newly updated state, this.setState comes with a second argument that will allow us to chain a callback once state has been updated.
Update your input change function to:
inputChange = (event) => { const { name, value } = event.target; console.log(name, value); let scheduleEvent = {...this.state.scheduleEvent}; console.log(scheduleEvent); scheduleEvent[name] = value; console.log(scheduleEvent); this.setState({ scheduleEvent }, () => { console.log(this.state.scheduleEvent); }); }
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.