簡體   English   中英

如何正確使用 react-router-dom No match 404?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM