React router v4 嵌套路由相对路径 [英] React router v4 nested route relative path

查看:34
本文介绍了React router v4 嵌套路由相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有反应路由器 v4 的组件到另一个组件,我想在第二个组件中添加另一个路由.

这是主要路线:

const Dashboard = () =>{返回 (<div><标题/><路由器><div><Route path="/" 精确组件={Wall}/><Route path="/challenge/:id" component={Challenge}/>

</路由器>

)}

这是挑战组件:

class Challenge 扩展组件 {...使成为() {返回 (...<路由器><div><Route path="/overview" 精确组件={Overview}/><Route path="/discussions" 精确组件={Discussions}/>

</路由器>...)}}

这对我不起作用..

唯一有效的选择是在挑战组件中包含/challenge/:id :

<Route path="/challenge/:id/overview" 精确组件={Overview}/><Route path="/challenge/:id/discussions" 精确组件={Discussions}/>

最后我想让路线看起来像这样,例如:

www.site.com/challenge/1/overview

www.site.com/challenge/1/discussions

但在每个嵌套路由中不包含完整路由.

解决方案

在您的 Challenge 组件中试试这个:

class Challenge 扩展组件 {...使成为() {const { match } = this.props;返回 (...<div><Route path={`${match.url}/overview`} 精确组件={Overview}/><路由路径={`${match.url}/discussions`} 精确组件={Discussions}/>

...)}}

请注意,您不需要添加新的 Router 实例,因为您的 Challenge 组件是您定义的 Router 实例的后代在您的顶级 Dashboard 组件中.

I have component with a react router v4 to anohter component, i want to add another routes in the second component.

this is the main route:

const Dashboard = () => {
  return (
    <div>
      <Header/>
      <Router>
        <div>
          <Route path="/" exact component={Wall} />
          <Route path="/challenge/:id" component={Challenge} />
        </div>
      </Router>
    </div>
  )
}

and this is the Challenge component:

class Challenge extends Component {
  ...

  render() {
    return (
      ...
        <Router>
          <div>
            <Route path="/overview" exact component={Overview} />
            <Route path="/discussions" exact component={Discussions} />
          </div>
        </Router>
      ...
    )
  }
}

and this is not working for me..

The only option that works is to include the /challenge/:id inside the challenge component:

<Route path="/challenge/:id/overview" exact component={Overview} />
<Route path="/challenge/:id/discussions" exact component={Discussions} />

in the end i want to make the route look like this for example:

www.site.com/challenge/1/overview

www.site.com/challenge/1/discussions

But without containing the full route within each nested route.

解决方案

Try this in your Challenge component:

class Challenge extends Component {
  ...

  render() {
    const { match } = this.props;
    return (
      ...
      <div>
        <Route path={`${match.url}/overview`} exact component={Overview} />
        <Route path={`${match.url}/discussions`} exact component={Discussions} />
      </div>
      ...
    )
  }
}

Note that you shouldn't need to add a new Router instance as your Challenge component is a descendant of the Router instance you defined in your top-level Dashboard component.

这篇关于React router v4 嵌套路由相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆