(I know that this is a simple question. Before posting I have tried to find the answer in previous questions. There are many questions regarding setState being asynchronous, about that you can use a callback function, etc., but I didn't find a question similar to the following).
When implementing a simple form in React, like the one that is shown here (under the controlled components
title, also copied below):
Since setState
is asynchronous, the example isn't guaranteed to work, right? (Since handleSubmit
prints this.state.value
, but there is no guarantee that it has been set already, when handleSubmit
is called).
Is there a way to ensure that handleSubmit
is called only after the state changes of all controlled components in a form have been done (and without using redux or something similar)?
Here is the code, copied from the reactjs.org (I am copying it to make sure it can be read even if the URL changes):
lass NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…