【问题标题】:How to set dynamic URL parameters to a variable value with react-router-dom如何使用 react-router-dom 将动态 URL 参数设置为变量值
【发布时间】:2022-11-20 03:18:21
【问题描述】:

我为此在网上看了很多,但似乎没有找到我的问题的正确答案。 如何将我的 URL 的一部分更改为来自例如用户输入的值。

我正在使用 react-router-dom v6 和 react 18.2

我尝试使用 UseParams 但它没有按预期工作。 我也尝试了 redirect 和 useHistory 但它没有导致想要的结果,也许我在我的场景中使用了错误

这是我到目前为止所拥有的:

应用程序.js


let persID = useContext(NumContext); // i use this since the Original value lays in another Script

return (


<Link to="/schedule/mySchedule/:persID" ><p className="NavText">My Timetable</p></Link> {/* persID is the dynamic URL part that should be replaced with a value out of varaible */}


<Route path="/schedule/mySchedule/:persID" element={<MySchedule />} />


)

我想要的是,如果变量的值为 2,它会指向 URL /schedule/mySchedule/2

我见过有人这样做,但他们不得不手动更换动态路线的一部分

我感谢任何建议或线索

【问题讨论】:

    标签: reactjs routes react-router-dom dynamic-routing


    【解决方案1】:

    我想要的是,如果变量的值为 2,它会指向 URL /schedule/mySchedule/2

    你可以使用模板字面量persID 参数包含在关联.

    <Link to={`/schedule/mySchedule/${persID}`} />
    

    更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-19
      • 2015-09-11
      • 1970-01-01
      • 2022-08-23
      • 1970-01-01
      • 2020-09-13
      • 2020-07-11
      • 2019-05-23
      相关资源
      最近更新 更多