React/Next.js登录表单提交时页面重载问题排查
问题:React/Next.js登录表单提交时页面自动重载,如何阻止?
我正在使用React/Next.js开发登录表单,点击提交按钮时能触发alert提示,但页面会自动重载,我希望实现提交时页面不重载的效果,请问问题出在哪里?
当前index.tsx代码:
import React from 'react'; import axios from 'axios'; const LoginForm = () => { const [formValue, setformValue] = React.useState({ email: '', password: '' }); const handleSubmit = (event) => { alert("its workinggg"); // we will fill this in the coming paragraph } const handleChange = (event) => { setformValue({ ...formValue, [event.target.name]: event.target.value }); } return ( <form onSubmit={handleSubmit}> <p>Login Form</p> <input type="email" name="email" placeholder="enter an email" value={formValue.email} onChange={handleChange} /> <input type="password" name="password" placeholder="enter a password" value={formValue.password} onChange={handleChange} /> <button type="submit" > Login </button> </form> ) }; export default LoginForm;
原因与解决方法
问题出在没有阻止HTML表单的默认提交行为——浏览器原生会在表单提交时触发页面重载/跳转,所以alert触发后页面会自动刷新。
只需要在handleSubmit函数里调用event.preventDefault(),就能阻止这个默认行为,让页面保持不重载:
修改后的handleSubmit代码片段:
const handleSubmit = (event) => { // 阻止表单默认提交行为 event.preventDefault(); alert("its workinggg"); // 后续可在此添加登录请求逻辑 }
完整修改后的代码:
import React from 'react'; import axios from 'axios'; const LoginForm = () => { const [formValue, setformValue] = React.useState({ email: '', password: '' }); const handleSubmit = (event) => { event.preventDefault(); alert("its workinggg"); // 示例:添加axios登录请求 // axios.post('/api/login', formValue) // .then(res => console.log(res.data)) // .catch(err => console.error(err)) } const handleChange = (event) => { setformValue({ ...formValue, [event.target.name]: event.target.value }); } return ( <form onSubmit={handleSubmit}> <p>Login Form</p> <input type="email" name="email" placeholder="enter an email" value={formValue.email} onChange={handleChange} /> <input type="password" name="password" placeholder="enter a password" value={formValue.password} onChange={handleChange} /> <button type="submit" > Login </button> </form> ) }; export default LoginForm;
内容的提问来源于stack exchange,提问作者virat sharma
相关产品推荐
相关产品推荐

