React Router - 两条路线之一

React Router - one of two routes

我知道标题可能含糊不清,所以我会尽量描述我的问题。

我正在做一个 WordPress 主题,我需要 link 分类和标签页面。它们的结构是/[categories|tags]/item。现在我只需要为这两个项目制定路线。我试过这样做:

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

但是有了这个我就分不清这是分类还是标签了。我不想使用 <Route path="/:type/:slug" component={Archives} />,因为当我需要使用嵌套页面时这可能会造成混淆。我也不想更改 url 方案。

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

<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

更新:不更改 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 {
         ...
      }    
   }
}