2016-03-08 196 views
2

我正在關注反應路由的this tutorial。我設法將它連接到我的數據存儲,它工作正常。Reactjs - 渲染登錄組件

令我困擾的是登陸頁面。我有set it up(小提琴)它的方式,當用戶轉到根頁面時,顯示鏈接到登錄。當用戶單擊該登錄名時,會顯示登錄表單組件。

我想避免點擊loginlink。當用戶導航到根頁面時,如果他未自動登錄,則顯示登錄組件。

Fiddle顯示我的無效嘗試使其工作。 的作品以前的代碼:

render() { 
return (
    <div> 
    <ul> 
     <li> 
     {this.state.loggedIn ? (
      <Link to="/logout">Log out</Link> 
     ) : (
      <Link to="/login">Sign in</Link> 
     )} 
     </li> 
     <li><Link to="/about">About</Link></li> 
     <li><Link to="/dashboard">Dashboard</Link> (authenticated)</li> 
    </ul> 
    {this.props.children || <p>You are {!this.state.loggedIn && 'not'} logged in.</p>} 
    </div> 
) 
} 

,這是我的嘗試:

render() { 
return (
    <Login data={this.state} /> 
) 
} 

這實際上呈現登錄組件,但會產生這個錯誤:

Uncaught TypeError: Cannot read property 'state' of undefined 

看來它斷開。

我現在打破我的頭在這一段時間,任何幫助表示讚賞

回答

1

在你的小提琴來看,我認爲這是你想要做的笏。

function requireAuth(nextState, replace) { 

    if (!auth.loggedIn()) { 
    replace({ 
     pathname: '/login', 
     state: { nextPathname: nextState.location.pathname } 
    }) 
    } 
} 

    render((
     <Router history={browserHistory}> 
      <Route path="/" component={App} onEnter={requireAuth} /> 
      <Route path="/login" component={Login} /> 
      <Route path="/logout" component={Logout} /> 
      <Route path="/about" component={About} /> 
      <Route path="/dashboard" component={Dashboard} /> 
     </Router> 
), document.getElementById('example')); 

順便說一句我刪除了您的路線我不認爲他們在您的設置中必要的嵌套,但如果你重新進行添加 我看到了你的提琴這個和平的代碼,所以實際上你需要的唯一的事情做的是的OnEnter = requireAuth上的應用程序, 如果您沒有登錄,您將去登錄,如果你是,你會去你的應用程序,

所以在我們的渲染,你可以做任何ü要

const App = React.createClass({ 
    render() { 
    return (
     <div> You are logged in </div> 
    ) 
    } 
}); 

旁註:U在這裏所做的唯一事情就是通過你的狀態對象的子組件

return (
    <Login data={this.state} /> 
) 

含義:

內登錄,this.props.data <財產 - 現在有,因爲這相同的價值觀登錄的父組件中的.state

+0

感謝您的回覆。當我使用你的代碼時,它可以工作,但有一個轉折點。成功登錄後,它只顯示「您已登錄」。我無法訪問任何其他路線,即使我在URL中鍵入它們......可能是什麼錯誤? –

+0

虐待更新我的答案 –

+0

因爲你有一個單獨的auth類,你的身份驗證可以在你的反應組件之外完成,你在onEnther中調用的函數已經爲你處理登錄流程,也就是說,如果你登陸APP 你的進入路徑= /那麼在哪裏假設你在,否則你將永遠被重定向到/登錄<記錄 - 您可以根據需要 –