React TypeScript:函数组件向类组件路由传值时遇类型错误
解决React Router v6类组件获取路由state的TypeScript错误
错误原因
你遇到的TypeScript错误根源有两点:
Home组件的Props类型定义为空对象,未包含location属性,TypeScript无法识别this.props.location的合法性。- React Router v6不再自动给类组件注入
location、history等路由相关props,即便不使用TypeScript,也无法直接通过this.props获取这些属性。
解决方案
方案一:自定义withRouter高阶组件
React Router v6移除了官方的withRouter,但可以自行封装一个,为类组件注入路由相关props:
- 创建
withRouter.tsx文件:
import { useLocation, useNavigate, useParams } from 'react-router-dom'; import React from 'react'; const withRouter = <P extends object>(Component: React.ComponentType<P>) => { const Wrapper = (props: Omit<P, 'location' | 'navigate' | 'params'>) => { const location = useLocation(); const navigate = useNavigate(); const params = useParams(); return <Component {...props as P} location={location} navigate={navigate} params={params} />; }; return Wrapper; }; export default withRouter;
- 修改
Home.tsx,使用该高阶组件并更新Props类型:
import { Component } from "react"; import "bootstrap/dist/css/bootstrap.min.css" import "./home.css" import { Location } from 'react-router-dom'; import withRouter from './withRouter'; // 更新Props类型,包含location属性 type Props = { location: Location<{ fromPage?: string }>; }; type State = { content: string; } class Home extends Component<Props, State> { constructor(props: Props) { super(props); this.state = { content: "" }; } componentDidMount() { const value = this.props.location.state?.fromPage; console.log("从RoleCategory页面传递的值:", value); } render() { return ( <div > <header className="main-body"></header> </div> ); } } // 用withRouter包裹组件,注入路由props export default withRouter(Home);
方案二:将类组件转为函数组件(推荐)
React Router v6更适配函数组件+钩子的写法,直接用useLocation获取路由state:
import React, { useEffect } from "react"; import "bootstrap/dist/css/bootstrap.min.css" import "./home.css" import { useLocation } from 'react-router-dom'; const Home = () => { const location = useLocation(); useEffect(() => { const value = location.state?.fromPage; console.log("从RoleCategory页面传递的值:", value); }, [location]); return ( <div > <header className="main-body"></header> </div> ); }; export default Home;
额外优化提示
你的RoleCategory组件中,useEffect的依赖数组为空,会导致isUserValid状态更新后无法触发跳转逻辑。建议将依赖补全:
useEffect(() => { if (!currentUser || !isUserValid) { navigate("/home", { state: { fromPage: "roleCategory" } }); } }, [currentUser, isUserValid, navigate]);
内容的提问来源于stack exchange,提问作者Edi-nano
相关产品推荐
相关产品推荐

