【问题标题】:How can sub paths be defined by omitting the parent path with React-Router-Dom?如何通过 React-Router-Dom 省略父路径来定义子路径?
【发布时间】:2021-12-28 05:49:08
【问题描述】:

所以,假设我有个人资料页面,它根据路径呈现不同的组件。 例如:

/profile/posts 在 Profile 中渲染 Posts 组件。

/profile/comments 在 Profile 中呈现 Comments 组件。

我通常先渲染"/profile"路径的Profile页面,然后在里面,根据上面提到的Routes渲染相关的组件。我想做的是,省略 Profile 内 Route 组件中定义的路径的 "/profile" 部分,只保留剩余部分。在不破坏路由的情况下如何做到这一点?

见下面代码中的cmets:

// App.js

// ...

<Switch>
    <Route exact path="/">
      <Home />
    </Route>
    <Route path="/profile">  // Profile page is rendered here
      <Profile />
    </Route>
</Switch>

// ...
// Profile.js

// ...

<Switch>
    <Route exact path="/profile/posts">  // I want to omit "/profile" part of the path.
      <Posts />
    </Route>
    <Route path="/profile/comments">  // I want to omit "/profile" part of the path.
      <Comments />
    </Route>
</Switch>
// ...

【问题讨论】:

    标签: javascript reactjs routes react-router react-router-dom


    【解决方案1】:

    在嵌套路由时,如果您不想“复制”路径详细信息,则可以从 match 对象中获取它们,特别是用于构建嵌套路由的 path 值。

    假设Profile是一个函数组件,使用useRouteMatch钩子访问当前匹配路由的path值。如果它是一个类组件,那么它必须访问路由道具才能获得this.props.match

    // Profile.js
    
    const { path } = useRouteMatch();
    
    // ...
    
    <Switch>
      <Route path={`${path}/posts`}> 
        <Posts />
      </Route>
      <Route path={`${path}/comments`}>
        <Comments />
      </Route>
    </Switch>
    
    // ...
    

    这是来自 `react-router-dom 的更深入的 nested routing demo

    【讨论】:

    • 我想做的是根本不写路径的第一部分。我的意思是,如果我已经在 Profile 页面中,这意味着路径已经包含“/profile”部分。否则,将不会呈现个人资料页面。也就是说,我认为为要在配置文件页面中呈现的组件编写绝对路径是不必要的重复。有没有办法将它们的路径设置为相对于父组件的路径?只是“/posts”或只是“/cmets”。或者可能只是第一个斜线之前的一个点,例如“./posts”
    • @noiseymur 不在react-router-dom v5 中。在 v6 中,这是一个重大变化,所有链接和路由都可以相对于渲染它们的父路由声明。不幸的是,在 v5 中,上面是处理嵌套路由的标准模式。使用这种模式,您实际上只需要指定最后一个路径段,例如,如果绝对路径是 "/parta/partb/partc/partd/etc/etc/targetsegment",那么您可能只需要指定 `${path}/targetsegment`
    猜你喜欢
    • 2018-03-01
    • 1970-01-01
    • 2022-07-12
    • 2022-12-05
    • 2017-12-16
    • 1970-01-01
    • 2016-12-29
    • 2019-12-11
    • 1970-01-01
    相关资源
    最近更新 更多