1

some code of index.tsx:

ReactDOM.render(
<MemoryRouter>
    <LocaleProvider locale={zhCn}>
        <App/>
    </LocaleProvider>
</MemoryRouter>,
document.getElementById('root') as HTMLElement
);

some code of App.tsx

interface AppProps{
  history?: any
}
....
public route() {
    if (!session.isLogin) {
        this.props.history.push('/');
    } else {
        this.props.history.push('/root')
    }
}
...
public render() {
    return (
        <Switch>
            <Route exact path='/' component={Login} />
            <Route exact path='/root' component={Root} />
        </Switch>
    )
}

When I write this, I will report wrong.Cannot read property 'push' of undefined,Then I modified the use of "withRouter" to modify it.

export default withRouter(App)

Also reported wrong: error TS2345: Argument of type 'typeof App' is not assignable to parameter of type 'ComponentType>'.

Type 'typeof App' is not assignable to type 'StatelessComponent>'.

Type 'typeof App' provides no match for the signature '(props: RouteComponentProps & { children?: ReactNode; }, context?: any): ReactElement | null'.

What is the problem?

Thank you

cc shen
  • 145
  • 1
  • 2
  • 12

1 Answers1

2

Your props in App.tsx needs to extend RouteComponentProps from react-router

for example:

interface AppProps extends RouteComponentProps {
    // rest of props
}

You should then be able to use:

this.props.history.push("/your-route");
Hayden Hall
  • 306
  • 3
  • 6
  • `interface AppProps extends RouteComponentProps{ history: any }` It will still report mistakes. error TS2339: Property 'history' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes, any, any>> & Read...'. – cc shen Sep 27 '18 at 09:08
  • You don't need to add ```history: any``` as part of your interface - it's part of ```RouteComponentProps```. How is your component declared? – Hayden Hall Sep 27 '18 at 09:15
  • `extends React.Component` – cc shen Sep 27 '18 at 09:35
  • The first type param in your component should be ```AppProps``` i.e. ```extends React.Component``` – Hayden Hall Sep 27 '18 at 10:18