使用history.push传参时props.location.state为undefined如何解决?
解决history.push传递state为undefined问题
常见原因及修复方案
1. 优先推荐使用useLocation钩子获取参数
不管是v5还是v6版本的react-router-dom,直接从组件props获取location属性都可能因为父组件未透传路由属性导致取值失败,改用内置的useLocation钩子取值更稳妥,修改Main组件代码如下:
import { useLocation } from "react-router-dom"; const Main = () => { const location = useLocation(); // 这里即可正常拿到传递的参数 console.log(location.state); }; export default Main;
2. 检查react-router-dom版本适配对应API
- 如果使用的是v5版本:
确认跳转逻辑没有问题,注意history.push的第二个参数直接就是state的完整值,你当前的写法传递后location.state的值为{state: 'test'},如果要直接拿到test,可以修改跳转代码为:
另外注意:state存储在会话历史中,刷新页面、手动输入地址访问都会导致state丢失,属于正常现象。history.push("/main", 'test'); - 如果使用的是v6版本:
v6已经移除了useHistoryAPI,替换为useNavigate,修改跳转代码如下:import { useNavigate } from "react-router-dom"; const navigate = useNavigate(); function handleSubmit(event) { event.preventDefault(); navigate("/main", { state: 'test'}); };
3. 检查Route组件写法(v5版本适用)
如果坚持从props获取location,确认Route绑定组件时没有截断属性传递:
- 用
component属性绑定是正常的,你当前的写法<Route path='/main' exact component={Main} />没有问题 - 如果用
render属性绑定,需要手动透传路由属性:<Route path='/main' exact render={(props) => <Main {...props} />} />
内容的提问来源于stack exchange,提问作者robs
相关产品推荐
相关产品推荐

