You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+Redux项目中新增元素渲染后一秒左右消失问题求助

React + Redux 新增元素渲染后自动消失的问题排查与解决

问题根源

核心原因是表单默认提交行为触发页面刷新:按钮的type="submit"会触发表单默认提交逻辑,页面刷新后Redux Store重新初始化,新增的书籍数据被重置,导致元素刚渲染就"消失"。

解决方案

1. 阻止表单默认提交行为

有两种常用实现方式:

方式一:在按钮点击事件中阻止默认行为

修改BookActions组件的按钮逻辑:

const BookActions = () => {
  const [title, setTitle] = useState('');
  const [author, setAuthor] = useState('');
  const dispatch = useDispatch();

  return (
    <form>
      <h2 className="addbook">ADD NEW BOOK</h2>
      <input
        type="text"
        placeholder="Book Title"
        onChange={(event) => setTitle(event.target.value)}
        value={title} {/* 添加受控绑定,确保状态同步 */}
      />
      <input
        type="text"
        placeholder="Author"
        onChange={(event) => setAuthor(event.target.value)}
        value={author} {/* 添加受控绑定 */}
      />
      <button
        onClick={(event) => {
          event.preventDefault(); // 关键:阻止表单默认提交
          // 生成唯一ID,避免重复冲突
          const newBook = {
            id: Date.now(),
            title: title,
            author: author,
            compleated: false,
            chapter: 1,
          };
          dispatch(addBook(newBook));
          // 清空输入框
          setTitle('');
          setAuthor('');
        }}
        className="bookbtn"
        type="submit"
      >
        Add Book
      </button>
    </form>
  );
};
方式二:给表单绑定onSubmit事件(更规范)
const BookActions = () => {
  const [title, setTitle] = useState('');
  const [author, setAuthor] = useState('');
  const dispatch = useDispatch();

  const handleSubmit = (event) => {
    event.preventDefault(); // 阻止默认提交
    const newBook = {
      id: Date.now(),
      title: title,
      author: author,
      compleated: false,
      chapter: 1,
    };
    dispatch(addBook(newBook));
    setTitle('');
    setAuthor('');
  };

  return (
    <form onSubmit={handleSubmit}>
      <h2 className="addbook">ADD NEW BOOK</h2>
      <input
        type="text"
        placeholder="Book Title"
        onChange={(event) => setTitle(event.target.value)}
        value={title}
      />
      <input
        type="text"
        placeholder="Author"
        onChange={(event) => setAuthor(event.target.value)}
        value={author}
      />
      <button className="bookbtn" type="submit">
        Add Book
      </button>
    </form>
  );
};

2. 补充优化点

  • 唯一ID生成:不要固定使用id:0,否则所有新增书籍ID重复,会导致渲染或数据冲突,推荐用Date.now()或uuid库生成唯一值。
  • Redux状态更新规范:虽然Redux Toolkit的Immer允许直接push,但更推荐不可变写法保持代码规范:
addBook: (state, action) => {
  state.value = [...state.value, action.payload]; // 替代push操作
},

内容的提问来源于stack exchange,提问作者David630

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 11:55:20