React Typescript: add location state to react router component

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

I have a normal route

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

that uses RouteComponentProps

4条回答
  •  粉色の甜心
    2020-12-21 08:19

    Previously, type checking was disabled for location state. That changed with https://github.com/DefinitelyTyped/DefinitelyTyped/issues/41674.

    The type defaults to unknown, but you can change it using generics:

    import { Location } from 'history';
    import { ReactElement } from 'react';
    import { StaticContext } from 'react-router';
    import { RouteComponentProps } from 'react-router-dom';
    
    type LocationState = {
        from: Location;
    };
    
    function LoginPage(
        props: RouteComponentProps<{}, StaticContext, LocationState>,
    ): ReactElement {
        props.history.push(props.location.state.from.pathname);
    }
    

提交回复
热议问题