React订阅表单问题:需点击提交存数据,现输入时频繁写入MongoDB
问题解决:React订阅表单每次输入字符都提交数据到MongoDB
问题原因
你把提交数据的axios.post请求写在了onChangeFormInput函数里,这个函数会在输入框每输入一个字符时触发,所以每次输入都会向MongoDB发送一条数据,导致异常。
解决方案
把数据提交逻辑移到按钮点击触发的validateNewsletterForm函数中,只有点击“Subscribe Now”按钮时才执行提交操作。同时可以添加简单的邮箱格式验证,避免无效数据提交。
修改后的前端表单部分
<form action='' onSubmit={(e) => e.preventDefault()}> <Input name='email' placeholder='Email' type='email' value={this.state.email} onChange={(e) => this.onChangeFormInput(e)} /> </form> <Button rightIcon={<ChevronRightIcon />} bg={'brand.300'} color={'black'} _hover={{ bg: 'brand.300', opacity: 0.8 }} _active={{ bg: 'brand.300', opacity: 0.8 }} onClick={this.validateNewsletterForm} > Subscribe Now </Button>
注:这里移除了外层的
Link标签,因为如果需要提交后跳转,可以在请求成功后通过代码实现;如果保留Link,点击按钮会直接跳转,可能导致请求还没完成就离开页面。如果必须保留跳转,可参考后续函数部分的处理。
修改后的函数部分
import axios from 'axios'; class Newsletter extends React.Component{ constructor(props){ super(props); this.state = { email:"", } this.validateNewsletterForm= this.validateNewsletterForm.bind(this); this.onChangeFormInput= this.onChangeFormInput.bind(this); } validateNewsletterForm(){ console.log("Button is clicked"); // 简单邮箱格式验证 const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (!emailRegex.test(this.state.email)) { console.log("请输入有效的邮箱地址"); return; } var NewsletterFormData = { email : this.state.email } console.log("Newslater Form Data ------------ ",NewsletterFormData.email); axios.post('http://localhost:3001/api/subscriptions',{ email:NewsletterFormData.email }) .then(function(response){ console.log(response); // 如果需要提交后跳转到Substack,在这里执行跳转 window.location.href = process.env.NEXT_PUBLIC_SUBSTACK_URL; }) .catch(function(error){ console.log(error) }); } onChangeFormInput(event){ console.log("Value is changing...",event); const value = event.target.value; console.log("The input : ",value); this.setState({email:value}) } }
关键修改点
- 移除
onChangeFormInput中的axios.post请求,只保留更新state的逻辑 - 在
validateNewsletterForm中添加邮箱验证和数据提交逻辑 - 若需要跳转,在请求成功的回调中通过
window.location.href实现,确保数据提交完成后再跳转
内容的提问来源于stack exchange,提问作者user16236267
相关产品推荐
相关产品推荐

