2017-10-29 147 views
0

這是我的方法來檢查用戶是否已經登錄或不。如果他們登錄了,我會呈現Newsfeed組件。如果沒有,我會呈現LoginPage組件。雖然用戶已經登錄,但我仍然可以看到登錄頁面,當我轉到路徑「/」時。我認爲獲取當前用戶需要一些時間,所以LoginPage仍然會顯示幾秒鐘。 我試圖找到一個更好的方法,但我還沒有找到任何人。誰能幫幫我嗎?提前謝謝React路由器Dom V4驗證檢查來渲染組件

class App extends Component { 
    componentWillMount() { 
    this.props.fetchCurrentUser(); 
    } 

    authRoute() { 
    return (
     <div> 
     <Header /> 
     <div className="app-container"> 
      <Route path="/" exact component={Newsfeed} /> 
      <Route path="/profile" exact component={Profile} /> 
      <Route path="/profile/:id" exact component={Profile} /> 
     </div> 
     </div> 
    ); 
    } 

    render() { 
    return (
     <BrowserRouter> 
     {this.props.user._id ? this.authRoute() : <Route path="/" exact component={LoginPage} />} 
     </BrowserRouter> 
    ); 
    } 
} 

function mapStateToProps(state) { 
    return { user: state.user }; 
} 

export default connect(mapStateToProps, { fetchCurrentUser })(App); 
+0

您每次都向服務器發送auth請求,因此您只需等待響應,即可顯示登錄頁面或彈出窗口(如果需要)。在leasr我在我的項目中使用這種方法 –

回答

0

以前我也在尋找這個問題,並最終遇到一個很好的樣板。你可以從這個react redux login flow中瞭解到,我覺得這樣更好。如果用戶已經登錄,它不會顯示登錄頁面。要了解,您可以看到readme.md,auth,js和從app.js調用您也可以嘗試根據需要更改某些邏輯。

+0

謝謝你的回答。我通過settimeout爲登錄組件做了一個不同的方法,因此它會在屏幕上顯示前等待100毫秒。不是一個好的方法,但它解決了這個問題。 – dnp1204