React TypeScript:react-router-dom 中 useLocation() 的正确类型
Posted
技术标签:
【中文标题】React TypeScript:react-router-dom 中 useLocation() 的正确类型【英文标题】:React TypeScript: Correct type for useLocation() from react-router-dom 【发布时间】:2020-08-23 09:19:45 【问题描述】:我正在努力寻找适合这种情况的类型。这是登录后重定向的简化版本。以下会产生编译器错误:
Property 'from' does not exist on type ' | from: pathname: string; ; '.
在location.state
的使用中添加as any
可修复编译器错误,但它很难看,并且linter 会抱怨。
import React from "react";
import useLocation from "react-router-dom";
const AuthLayer: React.FC = (props) =>
const location = useLocation();
const from = location.state || from: pathname: "/" ;
return <p></p>;
;
export default AuthLayer;
【问题讨论】:
【参考方案1】:您可以创建特定类型或接口来描述您的位置状态,然后在调用useLocation
挂钩时使用它:
import React from "react";
import useLocation from "react-router-dom";
interface LocationState
from:
pathname: string;
;
const AuthLayer: React.FC = (props) =>
const location = useLocation<LocationState>();
const from = location.state || from: pathname: "/" ;
return <p></p>;
;
export default AuthLayer;
【讨论】:
感谢您的回复。在 TypeScript 中进行了一些更改显示我的状态变量是“未知的”之后,状态变量正在破坏我。您提供的解决方案效果很好。【参考方案2】:您可以使用“历史”中的位置。
import React from "react";
import Location from "history";
import useLocation from "react-router-dom";
const AuthLayer: React.FC = (props) =>
const location = useLocation<Location>();
const from = location.state || from: pathname: "/" ;
return <p></p>;
;
export default AuthLayer;
【讨论】:
在对我来说是正确答案的位置的 console.log 之后,返回的对象是对应的【参考方案3】:类型断言可以在这里工作。
import React from "react";
import useLocation from "react-router-dom";
type LocationState =
from:
path: string;
const AuthLayer: React.FC = (props) =>
const location = useLocation();
const from = location.state as LocationState;
return <p></p>;
;
export default AuthLayer;
另外,请记住根据您的要求定义类型。
例如,您可能正在使用navigate(state.from)
。
为此将类型定义为-
type LocationState =
from : string;
【讨论】:
【参考方案4】:export interface LocationParams
pathname: string;
state: your_state_data_type;
search: string;
hash: string;
key: string;
//...
const location = useLocation<LocationParams>()
或者创建一个你可以在任何地方使用的泛型
// types.ts
export interface LocationParams<Data>
pathname: string;
state: Data;
search: string;
hash: string;
key: string;
// App.tsx
import LocationParams from './types.ts'
// ...
const location = useLocation<LocationParams<your_data_here>>()
【讨论】:
【参考方案5】:这会有点类型安全,因为如果 from
不在对象中而不是抛出错误,它将返回 undefined
。
import React from "react";
import useLocation from "react-router-dom";
type LocationState =
from:
path: string;
const AuthLayer: React.FC = (props) =>
const location = useLocation();
// ???
const from = (location.state as LocationState)?.from;
return <p></p>;
;
export default AuthLayer;
【讨论】:
以上是关于React TypeScript:react-router-dom 中 useLocation() 的正确类型的主要内容,如果未能解决你的问题,请参考以下文章
聊聊React的路由React-Routerreact-router-dom