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

使用useNavigate的navigate同时传递search与state参数失败问题

React Router navigate同时传递search和state时state为undefined的解决方法

你遇到的问题是因为React Router的navigate函数参数格式使用错误。当你以location对象(包含pathname、search)作为第一个参数调用navigate时,state并不属于location对象的属性,而是需要作为第二个参数(配置选项对象)的一部分传入。

单独传递location对象(带search)或者单独传递路径字符串+配置选项(带state)都能正常工作,但混合写法时,把state直接放在location对象里不会被React Router识别,导致目标组件中state值为undefined。

正确写法

将state从location对象中分离,放到第二个参数的配置选项里:

const stateParams = {
  param1: props.parentId,
};

navigate(
  {
    pathname: "/updatepage",
    search: `pageId=${props.pageId}`,
  },
  {
    state: stateParams,
  }
);

目标组件中获取state

在updatepage组件中,通过useLocation钩子正确获取state:

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

function UpdatePage() {
  const location = useLocation();
  console.log(location.state); // 此时能正常拿到param1的值
  return <div>...</div>;
}

这样就能同时生成指定格式的URL(包含pageId参数),并且成功传递state参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 00:27:04