2017-10-10 67 views
0

我一直在試驗反應路由器4在一個新的項目和我遇到的一個小問題是如何確保「子」路線不會從父路線繼承。反應路由器4:從根路線不同的模板

說我有一個頁面在根路線/呈現導航和儀表板,'/ profile'顯示用戶配置文件,與根路線共享模板,但我想重定向用戶/login,如果他們沒有記錄在RR4的結構中,來自根路由的模板將反映在登錄子路由上,但我有幾種方法可以獲得這種行爲,但它們都顯得很不守規矩,我想到的其中一種方法是使用RegEx。

不知道,最好的辦法應該是什麼..

<Router> 
    <div> 
     <Route path='/' component={() => <h1>Home Page</h1> }/> 
     <Route path='/login' component={() => <h1>Logins</h1> }/> 
     <Route path='/profile' component={() => <h1>Profile</h1> }/> 
    </div> 
</Router> 

登錄名和個人資料顯示Home Page,但我只想簡介做到這一點。

+1

您能否包含一些代碼,特別是您配置的路線? – MattD

+0

你可以展示你的孩子的路線是如何「與根路線共享模板」嗎? – palsrealm

+0

@MattD請找到更新 –

回答

0

您需要在您的應用程序組件添加Switch如下

<Router> 
    <div> 
     <Switch> 
     <Route path='/' component={<HomeTemplate/>}/> 
     <Route path='/login' component={() => <h1>Logins</h1> }/>   
     </Switch> 
    </div> 
</Router> 

創建HomeTempate成分,並添加Switch所有Route s表示需要導出模板。

<Header/> 
<TemplateSpecificComponents/> 
<Switch> 
     <Route path='/profile' render={() =><h1>Profile</h1> }/> 
     ... 
</Switch> 

從陣營路由器文檔(https://reacttraining.com/react-router/web/api/Switch):

<Switch>是因爲它呈現的路線完全是獨一無二的。相反,與位置匹配的每個<Route>都包含在內。

編輯:更新後在Profile中渲染HomeTemplate,但不在Login中。

+0

這種方法的問題是模板現在不能與配置文件頁面共享,我仍然希望部分維護模板共享屬性,同時防止它與幾頁共享 –

0

我曾想過解決這個問題的一種方法是使用HOC。例如

let template = function(WrappedComponent) { 
    return class extends React.Component { 
    render() { 
     return (
     <h1>Home Page</h1> 
     <WrappedComponent {...this.props}/> 
    ) 
    } 
    } 
} 

<Router> 
    <div> 
     <Switch> 
     <Route path='/' component={ template() } exact/> 
     <Route path='/login' component={() => <h1>Logins</h1> }/> 
     <Route path='/profile' render={ template(<h1>Profile</h1>) }/> 
     </Switch> 
    </div> 
</Router>