问题
(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>
);
}
}
回答1:
If you want to be sure you have a current value of an input inside handleSubmit use the passed SyntheticEvent to access inputs from a form.
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) {
event.preventDefault();
const form = event.currentTarget;
const inputValue = form.elements["user_name"].value;
alert('A name was submitted: ' + inputValue);
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" name="user_name" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
来源:https://stackoverflow.com/questions/49264268/can-i-avoid-submission-of-a-react-form-before-the-state-of-all-controlled-fields