【问题标题】:react-router Cannot read property 'push' of undefined?react-router无法读取未定义的属性'push'?
【发布时间】:2023-04-09 22:21:02
【问题描述】:

index.tsx 的一些代码:

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

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

写这个的时候会报错Cannot read property 'push' of undefined,然后我修改了使用"withRouter"来修改。

export default withRouter(App)

还报错: 错误 TS2345:“typeof App”类型的参数不可分配给“ComponentType>”类型的参数。

类型“typeof App”不可分配给类型“StatelessComponent>”。

类型 'typeof App' 不提供签名匹配 '(props: RouteComponentProps & { children?: ReactNode; }, context?: any): ReactElement |空'。

有什么问题?

谢谢

【问题讨论】:

  • 你能展示你如何使用

标签: reactjs typescript react-router-dom


【解决方案1】:

App.tsx 中的 props 需要从 react-router 扩展 RouteComponentProps

例如:

interface AppProps extends RouteComponentProps {
    // rest of props
}

你应该可以使用:

this.props.history.push("/your-route");

【讨论】:

  • interface AppProps extends RouteComponentProps{ history: any } 还是会报错。错误 TS2339:类型“IntrinsicAttributes & IntrinsicClassAttributes, any, any>> & Read...”上不存在属性“history”。
  • 您不需要将history: any 添加为界面的一部分 - 它是RouteComponentProps 的一部分。你的组件是如何声明的?
  • extends React.Component
  • 组件中的第一个类型参数应该是AppProps,即extends React.Component&lt;AppProps&gt;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-31
  • 1970-01-01
  • 2019-07-25
  • 1970-01-01
  • 2021-12-04
  • 2021-12-12
  • 1970-01-01
相关资源
最近更新 更多