在设置所有受控字段的状态之前,我可以避免提交 React 表单吗 [英] Can I avoid submission of a React form before the state of all controlled fields was set
问题描述
(我知道这是一个简单的问题.在发帖之前我已经尝试在以前的问题中找到答案.有很多关于 setState 是异步的问题,关于您可以使用回调函数等,但是我没有找到类似下面的问题)
在 React 中实现一个简单的表单时,如此处(在受控组件
标题,也复制在下面):
When implementing a simple form in React, like the one that is shown here (under the controlled components
title, also copied below):
由于 setState
是异步的,所以不能保证该示例有效,对吗?(因为 handleSubmit
打印 this.state.value
,但不能保证在调用 handleSubmit
时它已经设置了).
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).
有没有办法确保 handleSubmit
仅在表单中所有受控组件的状态更改完成后才被调用(并且不使用 redux 或类似的东西)?
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)?
这是从 reactjs.org 复制的代码(我将其复制到确保即使 URL 更改也可以读取它):
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>
);
}
}
推荐答案
如果您想确定 handleSubmit
中输入的当前值,请使用传递的 SyntheticEvent 到 从表单访问输入.
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>
);
}
}
这篇关于在设置所有受控字段的状态之前,我可以避免提交 React 表单吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!