【问题标题】:How to setup dynamic routing with React Router based on props received?如何根据收到的道具使用 React Router 设置动态路由?
【发布时间】:2020-08-02 19:26:22
【问题描述】:

我在 react JS 中创建了一个博客应用程序,并希望在导航到博客文章时更改 URL 路径。但是,我在使用 React Router Dom 的 Route 中使用 '/:id' 时遇到了问题。

导航到这两个 URL 时的示例:

Blog article URL:
https://website.com/myfirstblogpost/4582819

Profile page URL:
https://website.com/profile/902310

App.js 设置

<Route path="/:id/:id" component={BlogArticle} exact={true} />
<Route path="/profile/:id" component={Profile} exact={true}/>

通过此设置,我的博客文章将同时显示在博客文章路径和个人资料路径上。我该如何解决这个问题?是否可以渲染如下路线:

<Route path=`{/${blog.title}/${blog.id}}` component={BlogArticle} exact={true} />
<Route path=`{/profile/${user.id}`component={Profile} exact={true}/>

如果是这样,如果不是,还有什么其他解决方案?请注意,由于 SEO 原因,博客文章标题必须直接显示在第一个“/”之后,例如website.com/blogarticle

非常感谢各位!

亲切的问候,

弗里多

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    您需要做两处更改:

    第一:由于“个人资料”是硬编码的,您需要交换顺序并将其放在首位:

    <Route path="/profile/:id" component={Profile} exact={true}/>
    <Route path="/:id/:id" component={BlogArticle} exact={true} />
    

    这样,React Router 将首先搜索那些“硬编码”的 URL,然后检查变量。

    第二:如果它们不同,你的 URL 不能有两个相等的参数(第一个是字符串,可能是 slug。第二个是整数)。因此,您需要将其修改为:

    <Route path="/profile/:id" component={Profile} exact={true}/>
    <Route path="/:title/:id" component={BlogArticle} exact={true} />
    

    这可能会奏效!

    【讨论】:

    • 你是个传奇!这是工作!再次感谢 Guilherme!
    • 嗨,Guilherme,因为你是我的传奇。你能看看我遇到的这个问题吗? stackoverflow.com/questions/61405696/…非常感谢!!!
    • 哦@FridovanDriem,对不起,NEXT.JS 和 firebase 都没用过 :(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    相关资源
    最近更新 更多