我想定义某个无状态组件的 location.state
可以是什么类型。
我找到了几篇构建在 RouteComponentProps
类型上的文章,但我无法弄清楚细节。
假设在此示例中,我希望 location.state
属性的类型为
type StateType = {
id: number,
type: number
}
或者让 type` 甚至是一个枚举。可以实现吗?
import React from 'react';
import { withRouter, RouteComponentProps } from 'react-router-dom';
const Index = ({ location, history }) => {
return (
<div>Test</div>
)
}
export default withRouter(Index)
最佳答案
输入 RouteComponentProps
的 react-router
是泛型。这是您可以使用自定义类型定义位置状态的方式(我修改了您的示例):
import React from 'react';
import { withRouter, RouteComponentProps } from 'react-router-dom';
type StateType = {
id: number,
type: number
}
type IndexProps = RouteComponentProps<{}, {}, StateType>;
const Index: React.FC<IndexProps> = ({ location, history }) => {
return (
<div>{location.state && (
<ul>
<li>{location.state.id}</li>
<li>{location.state.type}</li>
</ul>
)}</div>
);
}
export default withRouter(Index);
一些要点:
- 你应该经常检查是否
location.state
已定义,可能会发生状态由于任何原因未通过 - 我们必须通过
React.FC
向组件本身添加正确的类型通用类型(不过,还有其他方法可以做到这一点...) -
RouteComponentProps
实际上得到三种类型被正确定义:- 首先(在我的示例中为空
{}
)-<Route />
's parameters 的类型 - 第二个(在我的示例中为空
{}
)-<StaticRouter />
's context 的类型 - 最后,第三个(在我的示例中为
StateType
)- 位置的状态类型
- 首先(在我的示例中为空
-
location
对象也可以在history.location
中找到, 但它不是键入的,不应该使用,如 stated in documentation :... The history object is mutable. Therefore it is recommended to access the location from the render props of
<Route>
, not fromhistory.location
. ...
关于reactjs - 使用 react-router-dom 在组件基础上键入 location.state 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59160131/