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

如何在 React Router 4 中管理身份驗證?

Patricia Arquette
發布: 2024-10-22 23:08:29
原創
304 人瀏覽過

How to Manage Authentication in React Router 4?

在React Router 4 中管理身份驗證

在React Router 版本4 中,與以前的版本相比,經過身份驗證的路由的實作需要不同的方法。

原始方法

以前,您可以對子元件使用多個 Route 元件,但現在不鼓勵這樣做。

<Route exact path="/&quot; component={Index} />
<Route path="/auth" component={UnauthenticatedWrapper}>
    <Route path="/auth/login" component={LoginBotBot} />
</Route>
<Route path="/domains" component={AuthenticatedWrapper}>
    <Route exact path="/domains" component={DomainsIndex} />
</Route>
登入後複製

正確實現

要實現經過身份驗證的路由,一種選擇是使用擴展Route 的自定義組件,並在渲染組件之前檢查身份驗證。

import React, {PropTypes} from "react";
import {Route} from "react-router-dom";

export default class AuthenticatedRoute extends React.Component {
  render() {
    if (!this.props.isLoggedIn) {
      this.props.redirectToLogin()
      return null
    }
    return <Route {...this.props} />
  }
}

AuthenticatedRoute.propTypes = {
  isLoggedIn: PropTypes.bool.isRequired,
  component: PropTypes.element,
  redirectToLogin: PropTypes.func.isRequired
}
登入後複製

替代方法

另一種方法是使用 Redirect 元件,它允許您根據經過驗證的屬性重新導向使用者。

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

然後您可以在路由中使用 PrivateRoute 元件:

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

以上是如何在 React Router 4 中管理身份驗證?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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