![](/img/trans.png)
[英]How to properly use useHistory () from react-router-dom?
[英]How to properly use react-router-dom No match 404?
我最近在使用 react-router-dom 時遇到了一個問題。 當我像這樣使用我的代碼時:
<BrowserRouter>
<div>
<Switch>
<Route path="/home" component={HOME} exact />
<Route path="/protected" component={PROTECTED} />
<Route component={NoMatch} />
</Switch>
</div>
</BrowserRouter>
NoMatch 路由組件工作正常,但是當我嘗試使用一些像這樣的 Auth 組件時,它不起作用:
<BrowserRouter>
<div>
<Switch>
<Route path="/home" component={HOME} exact />
<Auth>
<Route path="/protected" component={PROTECTED} />
</Auth>
<Route component={NoMatch} />
</Switch>
</div>
</BrowserRouter>
所以我閱讀了一些文檔和問題,並最終得出結論,我只需要使用 react-router-dom 組件。沒有外部組件或自定義組件。所以我的問題是解決這個問題。或者我'必須考慮另一種身份驗證路由方法。如果沒有解決方法,有人可以建議在<BrowserRouter/>
組件中進行這種身份驗證的最佳方法嗎?
React Router 只會在Switch
渲染單個組件。 如果路徑不匹配/home
,它將檢查第二個組件,即Auth
並始終呈現它。
您可以改為使用Route
組件的render
prop,以便第二個組件不會匹配除/protected
路由之外的任何路由。
<BrowserRouter>
<div>
<Switch>
<Route path="/home" component={HOME} exact />
<Route
path="/protected"
render={() => (
<Auth><PROTECTED /></Auth>
)}
/>
<Route component={NoMatch} />
</Switch>
</div>
</BrowserRouter>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.