4中实现经过身份验证的路由

4中实现经过身份验证的路由

本文介绍了如何在React Router 4中实现经过身份验证的路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图实现经过身份验证的路由,但发现React Router 4现在阻止了这种情况:

I was trying to implement authenticated routes but found that React Router 4 now prevents this from working:

<Route exact path="/" 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>

错误是:

在这种情况下,是什么?正确的方法来实现这个?

In that case, whats the correct way to implement this?

它出现在 react-router (v4)文档中,它表示类似

It appears in react-router (v4) docs, it suggests something like

<Router>
    <div>
    <AuthButton/>
    <ul>
        <li><Link to="/public">Public Page</Link></li>
        <li><Link to="/protected">Protected Page</Link></li>
    </ul>
    <Route path="/public" component={Public}/>
    <Route path="/login" component={Login}/>
    <PrivateRoute path="/protected" component={Protected}/>
    </div>
</Router>

但是在将一堆路线组合在一起时是否可以实现这一目标?

But isit possible to achieve this while grouping a bunch of routes together?

更新

确定经过一些研究,我想出了这个:

Ok, after some research, I came up with this:

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
}

在<$ c中调度操作是正确的$ c> render()感觉不对。用 componentDidMount 或其他一些钩子看起来不是很正确吗?

Isit correct to dispatch an action in render() it feels wrong. It doesnt really seem correct with componentDidMount or some other hook either?

推荐答案

您将要使用 Redirect 组件。这个问题有几种不同的方法。这是我喜欢的,有一个PrivateRoute组件,它接受一个 authed 道具,然后根据道具进行渲染。

You're going to want to use the Redirect component. There's a few different approaches to this problem. Here's one I like, have a PrivateRoute component that takes in an authed prop and then renders based on that props.

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

现在你的路线看起来像这样

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

如果你仍然感到困惑,我写了这篇文章可能有所帮助 -

If you're still confused, I wrote this post that may help - Protected routes and authentication with React Router v4

这篇关于如何在React Router 4中实现经过身份验证的路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 15:12