升级React Router v6后navigate跳转传参失败,目标组件props为undefined怎么办
解决方案
问题根因
react-router v6 中 navigate 函数的第二个参数为固定配置对象,仅支持 replace、state、preventScrollReset 三个顶层合法属性,你将自定义参数直接放在配置对象顶层不会被路由框架处理,因此无法在目标组件中获取。
同时你之前的取值方式存在两个误区:
useParams仅用于提取路由路径中声明的动态参数,比如path="/user/:id"中的id,不适用隐式传参场景- 自定义参数不会直接挂载到组件props或者
useLocation()返回的根对象上
修正步骤
1. 修改跳转传参写法
将需要传递的自定义参数统一放在配置对象的state字段下:
navigate("/authenticator", { state: { authMode: "login", username: user.username, } });
2. 目标组件取值
函数组件写法
直接使用useLocation钩子从state属性中提取参数,建议添加可选链和默认值处理,避免用户直接访问路由时报错:
import { useLocation } from "react-router-dom"; const Authenticator = () => { const location = useLocation(); const { authMode, username } = location.state || {}; // 后续业务逻辑 }
类组件写法(配合你自定义的withRouter)
如果Authenticator是类组件,用你自定义的withRouter包裹后,直接从props中取location.state即可:
import { withRouter } from './your-custom-withrouter-path'; class Authenticator extends React.Component { render() { const { authMode, username } = this.props.location.state || {}; // 后续业务逻辑 } } export default withRouter(Authenticator);
补充说明
通过state传递的参数会保存在浏览器会话历史中,用户刷新页面时参数不会丢失,但如果用户直接在地址栏输入/authenticator路径访问,没有经过跳转流程,state会为undefined,建议根据业务场景做容错处理。
内容的提问来源于stack exchange,提问作者Tempuslight
相关产品推荐
相关产品推荐

