简体   繁体   中英

How to properly use react-router-dom No match 404?

I've recently countered a problem while using react-router-dom. when i used my code like this:

<BrowserRouter>
  <div>            
    <Switch>
        <Route path="/home" component={HOME} exact />
        <Route path="/protected" component={PROTECTED} />
        <Route component={NoMatch} />
    </Switch>
  </div>
</BrowserRouter>

NoMatch route component worked fine, but when i tried to use some Auth component like this it didn't work:

<BrowserRouter>
  <div>            
    <Switch>
        <Route path="/home" component={HOME} exact />
      <Auth>
        <Route path="/protected" component={PROTECTED} />
      </Auth>
        <Route component={NoMatch} />
    </Switch>
  </div>
</BrowserRouter>

so I've read some docs and issues, and eventually reached to conclusion that i need to use only react-router-dom components.No external components or custom components.So my question here is there a work around this problem.Or I've to think of another approach for authentication routes.And if there is no work around, can someone suggest the best way to do this way of authentication inside <BrowserRouter/> component ?

React Router will only render a single component inside a Switch . If the path doesn't match /home , it will check the second component which is Auth and always render that.

You could instead use the render prop of the Route component so that the second component won't match any route except the /protected route.

<BrowserRouter>
  <div>            
    <Switch>
        <Route path="/home" component={HOME} exact />
        <Route
          path="/protected"
          render={() => (
            <Auth><PROTECTED /></Auth>
          )}
        />
        <Route component={NoMatch} />
    </Switch>
  </div>
</BrowserRouter>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM