简体   繁体   English

将 url 参数传递给 react-router 的 Link 组件的正确方法是什么?

[英]What's the proper way to pass url parameters to a react-router's Link component?

So far I've been replacing the url params' names manually when using a link component, for example:到目前为止,我一直在使用链接组件时手动替换 url 参数的名称,例如:

const userIdParam = ':userId'

const routes = {
   userDetails: `/users/${ userIdParam }`
}

<Link to={{
   pathname: routes.userDetails.replace(userIdParam, user.id)
}}/>

Does react router support passing the params as props into the to object or something like this?反应路由器是否支持将参数作为道具传递to object 或类似的东西? I'm looking for something similar to the following:我正在寻找类似于以下内容的内容:

const routes = {
   userDetails: `/users/:userId`
}

<Link to={{
   pathname: routes.userDetails,
   props: {
      userId: user.id
   }
}}/>

I've been going through the typings and the docs but can't really find anything.我一直在浏览打字和文档,但真的找不到任何东西。

Yes it does.是的,它确实。 If you want to navigate around then you can just use:如果你想四处导航,那么你可以使用:

<Link to="/redirect-to-this-url"></Link>

Incase, you want to pass props via the react-router then do this.如果您想通过 react-router 传递道具,请执行此操作。

// Initial Page
<Link to={{
    pathname: "redirected-route",
    state: {
        variable: value    // pass the extracted url params here
    }
}}
</Link>

The object passed in the state of Link would be accessible here by:在 Link 的 state 中传递的 object 可以通过以下方式访问:

// Redirected component
this.props.location.state    // { variable: "value" }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 创建包装组件并将其传递到React Router的推荐方法是什么? - What's the recommended way to create and pass a wrapped component to React Router? 将道具传递到React Router的链接组件 - Pass props to React Router's Link Component 用参数链接到路线的正确方法是什么? - What's the proper way to link to a route with parameters? 通过 react-router 处理带有斜线的路径的方法是什么? - What's the way to handle paths with slash via react-router? 使用反应路由器在 url 之间传递参数的正确方法是什么? - What is the proper way to pass parameters between urls using react router? react-router v4的Route不会将它的道具传递给组件 - 在React Typescript中 - react-router v4's Route doesn't pass it's props to component - in React Typescript React Js:将道具传递给 React Router 的 Link 组件错误 - React Js: Pass props to React Router's Link component Error React-intl在Safari v8.0.8上禁用react-router的链接组件onClick事件 - React-intl disable react-router's Link component onClick event on Safari v8.0.8 React-Router:为什么不呢 <Link> 组件的onClick处理程序调度我的动作? - React-Router: Why won't <Link> component's onClick handler dispatch my action? 有没有办法点击 div 容器包裹的 react-router 链接组件? - Is there a way to click div container wrapped react-router Link component?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM