React Typescript: add location state to react router component

前端 未结 4 1773
情歌与酒
情歌与酒 2020-12-21 07:52

I have a normal route

function LoginPage(props: RouteComponentProps): React.ReactElement {...
}

that uses RouteComponentProps

4条回答
  •  清歌不尽
    2020-12-21 07:57

    You can use the useLocation() hook providing a generic type, this way you can override the unknown type set by default in location.state.

    import { RouteComponentProps, useLocation } from 'react-router-dom';
    import React from 'react';
    
    interface stateType {
       from: { pathname: string }
    }
    
    const { state } = useLocation();
    
    console.log(state.from)
    
    

    It should work fine.

提交回复
热议问题