亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在React Router 4中實現經過身份驗證的路由?

如何在React Router 4中實現經過身份驗證的路由?

森林海 2019-12-12 12:59:10
我試圖實現經過身份驗證的路由,但是發現React Router 4現在阻止了它的工作:<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>錯誤是:警告:您不應使用<Route component>和<Route children>在同一路線上;<Route children>將被忽略在這種情況下,實現此目標的正確方法是什么?它出現在react-router(v4)文檔中,提示類似<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>但是在將一堆路線組合在一起時是否有可能實現這一目標?更新好吧,經過一番研究,我想到了這個: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}發出錯誤的動作是正確的render()感覺。似乎確實不正確,componentDidMount還是帶有其他掛鉤?
查看完整描述

3 回答

?
慕尼黑5688855

TA貢獻1848條經驗 獲得超2個贊

您將要使用該Redirect組件。有幾種不同的方法可以解決此問題。我喜歡的一個是,有一個PrivateRoute組件,該組件接受一個authed道具,然后根據該道具進行渲染。


function PrivateRoute ({component: Component, authed, ...rest}) {

  return (

    <Route

      {...rest}

      render={(props) => authed === true

        ? <Component {...props} />

        : <Redirect to={{pathname: '/login', state: {from: props.location}}} />}

    />

  )

}

現在你Route的可以看起來像這樣


<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 v4的受保護路由和身份驗證


查看完整回答
反對 回復 2019-12-12
?
鳳凰求蠱

TA貢獻1825條經驗 獲得超4個贊

Tnx Tyler McGinnis提供解決方案。我是根據Tyler McGinnis的想法提出的。


const DecisionRoute = ({ trueComponent, falseComponent, decisionFunc, ...rest }) => {

  return (

    <Route

      {...rest}


      render={

        decisionFunc()

          ? trueComponent

          : falseComponent

      }

    />

  )

}

您可以這樣實現


<DecisionRoute path="/signin" exact={true}

            trueComponent={redirectStart}

            falseComponent={SignInPage}

            decisionFunc={isAuth}

          />

DecisionFunc只是一個返回true或false的函數


const redirectStart = props => <Redirect to="/orders" />


查看完整回答
反對 回復 2019-12-12
  • 3 回答
  • 0 關注
  • 1192 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號