导航到没有反应路由器的 URL - "_this.props.history is undefined"错误



我正在尝试在加载应用程序时使用令牌检查身份验证实体,当用户未获得授权时,将他导航到登录页面。此方法插入到 Navbar 组件中,因为它位于应用中的每个页面上,因此将随时调用它。我试图将导航栏组件放在路由器内,但它不起作用。具有路由.js的应用程序:

<div className="App">
<HomeNavbar history={this.props.history}/>
<Router>
<Switch>
<Route exact path="/login" component={LoginPage}/>
<Route exact path="/addEvent" component={addEvent}/>
<Route exact path="/register" component={RegisterPage}/>
<Route exact path="/members" component={MembersList}/>
<Route exact path="/event/:id" component={EventDetails}/>
<Route exact path="/events" component={EventsList}/>
<Route exact path="/user/:id" component={UserDetails}/>
<Route path="/" component={EventsList}/>
</Switch>
</Router>
</div>

如您所见,HomeNavbar 在外面,但我希望它以这种方式显示,因为它显示在每个页面上。如何从该组件导航到另一个页面?

在这种情况下,您需要使用 React Router 中的withRouter方法。这将创建一个高阶组件,该组件接收所有路由器属性。因此,您将拥有以下内容,而不是HomeNavbar

import { withRouter } from 'react-router-dom'
// create a new home navbar with router.
const HomeNavbarWithRouter = withRouter(HomeNavbar)
// after creating this, your HomeNavbar component will receive all the router props // such as `history, match, location`
// Finally, mount the HomeNavbarWithRouter instead:
<HomeNavbarWithRouter />

我想你可以这样做

import React from 'react';
import { withRouter } from 'react-router-dom';
class HomeNavbar extends React.Component {
redner() { return (<div>Whatever should be here</div>); }
}
export default withRouter(HomeNavbar);

这将使历史记录在您的组件道具中可用。

最新更新