Redux状态无法保存表单提交数据问题求助
表单提交后Redux状态被页面刷新重置的问题解决
问题原因
你的Form组件中的按钮位于<form>标签内,HTML里<button>默认类型为submit,点击时会触发表单的默认提交行为——浏览器会刷新页面并发送GET请求(地址栏出现/?就是直接证据)。页面刷新会导致整个React应用重新初始化,Redux store也会被重置为初始状态,这就是状态短暂显示后消失、Redux DevTools短暂提示“No store found”的原因。
而Login组件的按钮不在<form>标签内,不会触发表单默认提交行为,因此能正常修改Redux状态。
解决方案
以下三种方法任选其一即可:
方法1:阻止按钮的默认行为
修改按钮的onClick事件,添加e.preventDefault()拦截表单提交:
import { useState } from 'react' import { useDispatch } from 'react-redux' import { newPost } from '../features/postSlice' const Form = () => { const [post, setPost] = useState({ title: "", body: "" }) const dispatch = useDispatch() return ( <> <form> <h1>Form</h1> <label>Title:</label> <input type="text" value={post.title} onChange={(e) => setPost({ ...post, title: e.target.value })} /> <label>Body:</label> <textarea cols={25} rows={10} type="text" onChange={(e) => setPost({ ...post, body: e.target.value })} /> <button onClick={(e) => { e.preventDefault(); // 阻止默认表单提交 dispatch(newPost({ title: post.title, body: post.body })) }} > Add Post </button> </form> </> ) } export default Form
方法2:给表单添加onSubmit事件(推荐,语义化)
将提交逻辑移到表单的onSubmit事件中,统一阻止默认行为,同时将按钮设为type="submit":
import { useState } from 'react' import { useDispatch } from 'react-redux' import { newPost } from '../features/postSlice' const Form = () => { const [post, setPost] = useState({ title: "", body: "" }) const dispatch = useDispatch() const handleSubmit = (e) => { e.preventDefault(); dispatch(newPost({ title: post.title, body: post.body })) } return ( <> <form onSubmit={handleSubmit}> <h1>Form</h1> <label>Title:</label> <input type="text" value={post.title} onChange={(e) => setPost({ ...post, title: e.target.value })} /> <label>Body:</label> <textarea cols={25} rows={10} type="text" onChange={(e) => setPost({ ...post, body: e.target.value })} /> <button type="submit">Add Post</button> </form> </> ) } export default Form
方法3:将按钮类型设为button
显式设置按钮的type="button",使其不会触发表单提交:
import { useState } from 'react' import { useDispatch } from 'react-redux' import { newPost } from '../features/postSlice' const Form = () => { const [post, setPost] = useState({ title: "", body: "" }) const dispatch = useDispatch() return ( <> <form> <h1>Form</h1> <label>Title:</label> <input type="text" value={post.title} onChange={(e) => setPost({ ...post, title: e.target.value })} /> <label>Body:</label> <textarea cols={25} rows={10} type="text" onChange={(e) => setPost({ ...post, body: e.target.value })} /> <button type="button" // 显式指定按钮类型,避免触发表单提交 onClick={() => { dispatch(newPost({ title: post.title, body: post.body })) }} > Add Post </button> </form> </> ) } export default Form
验证效果
修改完成后,点击“Add Post”按钮,页面不会刷新,Redux状态将持久保存,Redux DevTools也不会再出现“No store found”的提示。
内容的提问来源于stack exchange,提问作者Forrest Morrison
相关产品推荐
相关产品推荐

