React Router - 两条路由之一

时间:2016-04-22 06:21:12

标签: wordpress reactjs 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 个答案:

答案 0 :(得分:1)

您可以使用查询来确定类型:

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

然后通过以下方式访问档案视图中的查询:

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

更新:不更改网址方案

...

<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 {
         ...
      }    
   }
}  
相关问题