如何在React中实现表单重复提交:重置提交状态的解决方案
Hey there! I totally get what you're dealing with—right now once you set formSubmit to true, there's no way to flip it back to false, so your RM component won't re-trigger for subsequent submissions. Let's fix this with a simple callback approach.
核心思路
The key is to have your RM component notify the parent App component when it's finished processing the form data. Then, you can reset formSubmit to false in that notification callback, allowing users to submit the form again.
修改步骤
给
RM组件添加完成回调
更新RM的渲染代码,传入一个onComplete属性,用来重置formSubmit状态:{this.state.formSubmit && <RM search1={this.state} onComplete={() => this.setState({formSubmit: false})} />}在
RM组件处理完成时触发回调
在RM组件内部,当数据处理完成(比如API请求结束、数据转换完成等),调用onComplete属性。如果RM是类组件,示例如下:class RM extends React.Component { componentDidMount() { // 模拟数据处理逻辑(替换成你实际的业务代码) fetch('/api/process-form', { method: 'POST', body: JSON.stringify(this.props.search1) }) .then(response => response.json()) .then(data => { // 处理返回的数据 console.log('数据处理完成:', data); // 通知父组件处理完毕 this.props.onComplete(); }) .catch(error => { console.error('数据处理出错:', error); // 即使出错也重置状态,让用户可以重新提交 this.props.onComplete(); }); } render() { // RM组件的渲染逻辑 return <div>正在处理你的请求...</div>; } }如果
RM是函数组件,用useEffect来处理:function RM({ search1, onComplete }) { useEffect(() => { const processData = async () => { try { const response = await fetch('/api/process-form', { method: 'POST', body: JSON.stringify(search1) }); const data = await response.json(); console.log('数据处理完成:', data); } catch (error) { console.error('数据处理出错:', error); } finally { // 无论成功失败,都重置父组件状态 onComplete(); } }; processData(); }, [search1, onComplete]); return <div>正在处理你的请求...</div>; }可选:提交后清空表单输入
如果需要在提交后清空输入框,可以在onComplete回调里同时重置表单字段:<RM search1={this.state} onComplete={() => this.setState({ formSubmit: false, nameinput: "", // 注意要和输入框的name属性对应 surnameinput: "" })} />
小提醒
我注意到你的state里定义了BO_course和BO_max_speed,但输入框的name属性是nameinput和surnameinput——这会导致输入值无法正确存入state哦。你可以把初始state改成和输入框name匹配的字段:
this.state = { nameinput: "", surnameinput: "", formSubmit: false };
这样handleInput就能正确更新输入对应的状态了。
内容的提问来源于stack exchange,提问作者munkaboo

