[英]Navigate to the URL without react-router - “_this.props.history is undefined” error
I'm trying to check authentity using tokens while loading the app and when user is not authorized navigate him to the log-in page. 我正在尝试在加载应用程序时使用令牌检查真实性,并且当用户未获得授权时,将其导航到登录页面。 This method is inserted into Navbar component because it is on every page in the app, so it will be called any time.
此方法已插入到Navbar组件中,因为它位于应用程序的每个页面上,因此可以随时调用。 I tried to place the navbar component inside the Router but it doesn't work.
我试图将navbar组件放置在路由器内,但是它不起作用。 The App.js with routing:
带有路由的App.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>
As you can see HomeNavbar is outside the but I want it that way because it displays on every page. 如您所见,HomeNavbar在之外,但我希望这样,因为它显示在每个页面上。 How can I navigate to the other page from that component?
如何从该组件导航到另一个页面?
In this case, you need to use the withRouter
method from React Router. 在这种情况下,您需要使用React Router中的
withRouter
方法。 This will create a higher order component which receives all the router props. 这将创建一个接收所有路由器道具的高阶组件。 So instead of
HomeNavbar
, you'll have this: 因此,您将拥有以下内容而不是
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 />
I think you can do it like this 我想你可以这样
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);
This will make history available in your component props. 这将使历史记录在您的组件道具中可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.