2017-06-03 68 views
-1

我不知道爲什麼不管isAuthenticated是否爲false,它總是以渲染而不是擊中。當isAuthenticated爲false時,你會認爲它顯然會觸發重定向,但事實並非如此。有條件不被擊中 - 條件呈現React組件

class ProtectedRoute extends Component { 
    render() { 
    console.log(`ProtectedRoute: isAuthenticated: ${this.props.isAuthenticated}`) 
    const ComponentToRender = this.props.component, 
    RouteToRender = (
     <Route 
     {...this.props} 
     render={() => 
      (this.props.isAuthenticated ? (<ComponentToRender {...this.props} />) : 
      (<Redirect 
       to={{ 
       pathname: '/login', 
       state: {from: this.props.location 
       }}} 
      />))} 
     />) 

     return (RouteToRender) 
    } 
} 

這是我看到RouteToRender在WebStorm當我調試: enter image description here

我所做的是隻強制重定向和我注意到,我也不得不刪除{...這一點。道具}和狀態:{來源:this.props.location}這工作:

class ProtectedRoute extends Component { 
    render() { 
    console.log(`ProtectedRoute: isAuthenticated: ${this.props.isAuthenticated}`) 
    const ComponentToRender = this.props.component, 
    RouteToRender = (
     <Route 
     render={() => 
      (<Redirect 
      to={{ 
       pathname: '/login' 
       }} 
      />)} 
     />) 

     return (RouteToRender) 
    } 

所以它可能是與事實,我繼承道具的問題。因此,這裏就是調用看起來像這樣利用這個組件:

<ProtectedRoute component={DashboardContainer} path='/dashboard' /> 

所以我接受了這些道具也來了......(組件和路徑)

THE FIX

<Route 
      render={({this.props}) => 
      (this.props.isAuthenticated ? (<ComponentToRender {...this.props} />) : 
       (<Redirect 
       to={{ 
        pathname: '/login', 
        state: {from: this.props.location 
        }}} 
       />))} 
     />) 

實際上它並沒有完全解決它,但至少它不是在!isAuthenticated時渲染組件。但現在我最後一次更改導致另一個問題,如果isAuthenticated是真實的,它不是渲染可能,因爲我從它刪除{... this.props}不再有路徑

回答

0

您正在發送組件和呈現作爲道具組件的道具。由於組件prop是可用的,路由呈現該組件而不是觸發呈現。

+0

啊我想我現在看到......唉 – PositiveGuy

+0

以及我試圖模仿這裏的PrivateRoute功能:https://reacttraining.com/react-router/web/example/auth-workflow – PositiveGuy

+0

我想我有一個修復它,謝謝你的幫助 – PositiveGuy