元芳怎么了
2021-06-15 17:42:16
我正在嘗試在加載應(yīng)用程序時使用令牌檢查真實性,當(dāng)用戶未經(jīng)授權(quán)時,將他導(dǎo)航到登錄頁面。這個方法被插入到 Navbar 組件中,因為它在應(yīng)用程序的每個頁面上,所以它會隨時被調(diào)用。我試圖將導(dǎo)航欄組件放在路由器中,但它不起作用。帶有路由的 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>正如您所看到的,HomeNavbar 位于 之外,但我希望這樣,因為它顯示在每個頁面上。如何從該組件導(dǎo)航到另一個頁面?
2 回答

肥皂起泡泡
TA貢獻1829條經(jīng)驗 獲得超6個贊
在這種情況下,您需要使用withRouterReact Router 中的方法。這將創(chuàng)建一個接收所有路由器道具的高階組件。所以,而不是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 />
添加回答
舉報
0/150
提交
取消