reactjs - 使用 react-router-dom 在组件基础上键入 location.state 属性

标签 reactjs typescript react-router-dom

我想定义某个无状态组件的 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)

最佳答案

输入 RouteComponentPropsreact-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 实际上得到三种类型被正确定义:
  • 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 from history.location. ...

关于reactjs - 使用 react-router-dom 在组件基础上键入 location.state 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59160131/

相关文章:

reactjs - React Admin : Can I use another field for <ReferenceInput>, 除了 "id"之外?

node.js - Mailtrap 的 Nodemailer 选项(错误 : too many emails per second)

typescript - 如何强制泛型

javascript - Angular 2+ 添加或删除属于另一个组件的元素的类

reactjs - 为什么对象作为 react 子对象无效?什么是有效的 children 的 react 以及为什么?

node.js - Reactjs 开发服务器无法在 macos catalina 上启动

javascript - 使用react-router响应页面布局

reactjs - 索引路由旁边的 React router v4 通配符

javascript - 使用 React、React DOM 和 React Router 的外部时,React Router 4 出现问题

javascript - React router最新版本中,如何在首页嵌套路由 "/"