React报错Property 'state' not existing on type 'Location'
问题原因
两个核心问题触发TypeScript类型报错:
- 导入来源错误:
Login组件中useLocation从react-router导入,实际项目使用react-router-dom的路由能力,跨包导入时TS会将返回值识别为浏览器原生Location类型,原生浏览器Location接口本身不存在state属性。 - 缺少类型声明:
react-router-dom的useLocation默认将state推断为unknown类型,未明确声明结构时TS无法识别state上挂载的自定义业务属性。
解决步骤
1. 修正导入路径
将Login组件中useNavigate、useLocation的导入源从react-router改为react-router-dom,和项目其他路由组件的导入保持一致:
// 错误导入 // import { useNavigate, useLocation } from 'react-router'; // 正确导入 import { useNavigate, useLocation } from 'react-router-dom';
2. 为location声明state的类型结构
给useLocation传入泛型参数,明确state上的字段结构,TS即可正常做类型校验,不会再报属性不存在错误。
修改后的Login组件完整代码:
import { useEffect } from "react"; import { Authenticator, useAuthenticator, View } from '@aws-amplify/ui-react'; import '@aws-amplify/ui-react/styles.css'; import { useNavigate, useLocation } from 'react-router-dom'; // 声明location.state的类型结构 type LoginLocationState = { from?: { pathname: string; } } export function Login() { const { route } = useAuthenticator((context) => [context.route]); // 传入泛型标注state类型 const location = useLocation<LoginLocationState>(); const navigate = useNavigate(); let from = location.state?.from?.pathname || '/'; useEffect(() => { if (route === 'authenticated') { navigate(from, { replace: true }); } }, [route, navigate, from]); return ( <View className="auth-wrapper"> <Authenticator></Authenticator> </View> ); }
3. 补充RequireAuth组件类型(消除隐式any报错)
RequireAuth组件的children参数未声明类型,会触发TS隐式any校验错误,建议补充对应类型:
import { ReactNode } from 'react'; import { useLocation, Navigate } from 'react-router-dom'; import { useAuthenticator } from '@aws-amplify/ui-react'; // 声明组件Props类型 type RequireAuthProps = { children: ReactNode; } export function RequireAuth({ children }: RequireAuthProps) { const location = useLocation(); const { route } = useAuthenticator((context) => [context.route]); if (route !== 'authenticated') { return <Navigate to="/login" state={{ from: location }} replace />; } return children; }
兜底排查
如果完成以上修改后仍存在类型报错,检查项目依赖:
- 确认
react-router和react-router-dom版本一致,避免多版本共存导致类型冲突 - 若使用v5及更早版本的react-router-dom,需要确认已安装对应版本的
@types/react-router-dom类型包;v6及以上版本已内置TS类型,无需额外安装类型包。
内容的提问来源于stack exchange,提问作者Mark
相关产品推荐
相关产品推荐

