【问题标题】:Typing the location.state property on a component basis using react-router-dom使用 react-router-dom 在组件基础上键入 location.state 属性
【发布时间】:2020-03-28 07:37:56
【问题描述】:

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

【问题讨论】:

    标签: reactjs typescript react-router-dom


    【解决方案1】:

    react-router 的类型 RouteComponentProps 是泛型类型。这是您可以使用自定义类型定义位置状态的方式(我修改了您的示例):

    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

      ...历史对象是可变的。因此建议从&lt;Route&gt; 的渲染道具访问位置,而不是从history.location。 ...

    【讨论】:

      【解决方案2】:

      您可以使用泛型类型Location 并简单地使用StateType 扩展它。

      import { Location } from 'history';
      
      type LocationProps = Location<StateType>;
      

      记得正确输入你的组件:

      interface IndexProps {
         location: LocationProps;
         classes: // your type
         history: // your type
      }
      
      const Index = ({ classes, location, history }: IndexProps) => {
      

      【讨论】:

      • 所以这样我也必须定义历史。使用默认类型不能留空吗?
      • @MartinSchmelzer 试着把它留空。如果 tsc 不会责备,那很好。如果没有,您可能还需要输入 History :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-22
      • 1970-01-01
      • 2020-12-22
      • 2020-06-14
      • 2022-06-29
      • 1970-01-01
      • 2021-04-14
      相关资源
      最近更新 更多