首頁 > web前端 > js教程 > 主體

如何在 React Router 4 中實現認證路由?

Mary-Kate Olsen
發布: 2024-10-22 22:57:03
原創
858 人瀏覽過

How to Implement Authenticated Routing in React Router 4?

React Router 4 中的經過驗證的路由

React Router 4 中的經過驗證的路由需要與先前版本不同的方法。 React Router 4 不再支援具有元件和子屬性的巢狀路由,這使得實現經過驗證的路由變得更具挑戰性。

解決方案:使用重定向元件

來實現經過驗證路由,您可以使用重定向元件。 Redirect 元件會根據給定條件將使用者重新導向到不同的路徑。

考慮以下PrivateRoute 元件:

<code class="javascript">function PrivateRoute ({component: Component, authed, ...rest}) {
  return (
    <Route
      {...rest}
      render={(props) => authed === true
        ? <Component {...props} />
        : <Redirect to={{pathname: '/login', state: {from: props.location}}} />}
    />
  )
}</code>
登入後複製

如果使用者經過驗證(anthed),此元件將呈現指定的元件===真);否則,它會將使用者重新導向到登入頁面。

用法:

現在,您可以在路由中使用PrivateRoute 元件,如下所示:

<code class="javascript"><Route path='/' exact component={Home} />
<Route path='/login' component={Login} />
<Route path='/register' component={Register} />
<PrivateRoute authed={this.state.authed} path='/dashboard' component={Dashboard} /></code>
登入後複製

在此範例中,儀表板路由的PrivateRoute 會將未經驗證的使用者重新導向至登入頁面。

替代解決方案:調度操作

另一種方法,可能不太理想的是在 AuthenticatedRoute 元件的 render 方法中調度一個操作。這可能看起來像:

<code class="javascript">export default class AuthenticatedRoute extends React.Component {
  render() {
    if (!this.props.isLoggedIn) {
      this.props.redirectToLogin()
      return null
    }
    return <Route {...this.props} />
  }
}</code>
登入後複製

當使用者未登入時,此方法會觸發到登入頁面的重定向,但它可能感覺不如使用重定向元件那麼優雅。

以上是如何在 React Router 4 中實現認證路由?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!