2016-04-22 30 views
0

我知道標題可能含糊不清,所以我會盡力描述我的問題。React Router - 兩條路線之一

我正在做一個WordPress主題,我需要鏈接到兩個類別和標籤頁面。他們的結構是/[categories|tags]/item。現在我只需要爲這兩個項目製作路線。我試過這樣做:

<Route path="/category/:slug" component={Archives} /> 
    <Route path="/tag/:slug" component={Archives} /> 

但與此我沒有任何區別這是一個類別或標籤。我不想和<Route path="/:type/:slug" component={Archives} />一起去,因爲當我需要使用嵌套頁面時,這可能會令人困惑。我也不想改變網址方案。

回答

1

您可以使用查詢來確定是什麼類型:

this.props.location.query // you could set up some conditional logic based on type 

UPDATE:

<Link to={{ pathname: '/category/[slug]', query: { type: 'category' } }} activeClassName="active">Some Link</Link> 

通過再訪問查詢您的檔案觀點不改變URL方案

... 

<Route path="/category/:slug" component={Archives} /> 
<Route path="/tag/:slug" component={Archives} /> 

// Then in Archives component you could do 

class Archive extends React.Component { 
    ... 
    render() { 
     const path = this.props.location.pathname; 
     const category = path.indexOf('/category/') !== -1; 
     const tag = path.indexOf('/tag/') !== -1; 
     ... // some logic based on tag and category 
     return { 
     ... 
     }  
    } 
} 
+0

您的解決方案將'type = category'添加到url,我想避免這種情況。 –

+0

我自己使用了類似的解決方案,但是,使用'location.pathname'是正確的方法。 –