Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

reactjs - React Typescript: add location state to react router component

I have a normal route

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

that uses RouteComponentProps from react-router-dom.

Strangely there were no issues for a long time with this component, but now it is failing to compile on travis-ci when I use history.push(location.state.from.pathname) saying Property 'from' does not exist on type '{}'.

I set this state in my PrivateRoute component that is pretty standard with a Redirect

<Redirect
  to={{ pathname: '/login', state: { from: props.location } }}
/>

How can I update the typing for location to include a from object with pathname: string;

EDIT:

The solution was to add

COPY yarn.lock /usr/src/app/

to my Dockerfile after I copied the package.json over.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...