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

React中导航至当前路由页面时如何修改useState值?

问题:提交表单后导航回当前页面无法重置输入框状态

我希望在handleSubmit函数中,显示toast.success提示信息后,导航至当前页面(/addType路由)时将collection_name的useState值设置为空字符串。目前页面可正常导航,但该状态值未发生变化,尝试调用setCollection(null)也无效果,恳请提供帮助。

相关代码

AddCollection组件

const AddCollection = () => {
  const [collection_name, setCollection] = useState("");

  const navigate = useNavigate();

  function handleSubmit(e) {
    e.preventDefault();
    axios
      .post("http://localhost:8000/api/addCollection", {
        collection_name,
      })
      .then((res) => {
        toast.success(res.data.message);
        navigate('/addType');
       })
      .catch((err) => {
        //console.log(err.response.data.error);
       toast.error(err.response.data.error)
      });
  }
  return (
    <Layout>
      <h1>Add Book Type</h1>
      <ToastContainer />
      <form className={styles.form} onSubmit={handleSubmit}>
        <div className={styles.grid}>
          <div>
            <label htmlFor="">Name</label>
            <input
              type="text"
              placeholder="Enter Type.."
              className="form-control"
              name="collection_name"
              onChange={(e) => setCollection(e.target.value)}
            />
          </div>
        </div>
        <input type="submit" value="Add" className="btn" />
      </form>
    </Layout>
  );
};

export default AddCollection;

App.js路由配置

<BrowserRouter>
   <Routes>
    <Route path="/" element={<Home />}></Route>
    <Route path="/addType" element={<AddCollection />}></Route>
    <Route path="/allType" element={<AllCollection />}></Route>
    <Route path="/add" element={<AddBook />}></Route>
    <Route path="/books" element={<AllBook />}></Route>
    <Route path="/addBookCollection" element={<AddBookCollection />}></Route>
    <Route path="/edit/:id" element={<EditBook />}></Route>
    <Route path="/type/:name" element={<TypeWiseBook />}></Route>
    <Route path="/search" element={<SearchPage />}></Route>
    <Route path="/book/:id" element={<SingleBook />}></Route>
   </Routes>
</BrowserRouter>

原因分析

当调用navigate('/addType')导航到当前路由时,React Router默认不会重新挂载组件,组件的原有状态会被保留,此时调用setCollection可能因为组件生命周期的原因无法生效,或者因为没有触发组件重新渲染而看不到变化。

解决方案

方案1:直接重置状态(推荐)

不需要导航到当前页面,在请求成功后直接重置状态即可:

.then((res) => {
  toast.success(res.data.message);
  setCollection(""); // 直接将状态置为空字符串
  // 移除navigate('/addType'),因为本来就在当前页面
})

方案2:强制组件重新挂载

通过给组件添加唯一key,让React在导航时重新渲染组件:

  1. 修改App.js的路由,添加一个包装组件:
import { useLocation } from 'react-router-dom';

const AddCollectionWrapper = () => {
  const location = useLocation();
  // 用导航时传递的key或时间戳作为组件的key
  return <AddCollection key={location.state?.key || Date.now()} />;
};

// 更新路由配置
<Route path="/addType" element={<AddCollectionWrapper />}></Route>
  1. 在handleSubmit中导航时传递唯一key:
.then((res) => {
  toast.success(res.data.message);
  navigate('/addType', { state: { key: Date.now() } });
})

方案3:监听路由变化重置状态

使用useEffect监听路由,每次进入/addType路由时重置状态:

import { useLocation } from 'react-router-dom';

const AddCollection = () => {
  const [collection_name, setCollection] = useState("");
  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    // 路由变化时重置输入框状态
    setCollection("");
  }, [location]);

  // ... 其余代码保持不变
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 08:45:56