通过 React-Router v4 <Link/> 传递值 [英] Passing values through React-Router v4 <Link />

查看:18
本文介绍了通过 React-Router v4 <Link/> 传递值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:如何通过 React-Router 的 Link 组件传递 prop 或单个值(如 _id),并在端点处捕获它?

Question: How can I pass a prop or a single value, like an _id, through React-Router's Link component, and catch it at the endpoint?

这就是我的意思:假设我们在页面/a 上.该链接会将用户带到/b.因此.现在,我需要通过链接传递一个 _id,从/a 到/b.

This is what I mean: Let's say we are on page /a. The Link will take the user to /b. As such <Link to='/b'>. Now, I need to pass an _id through the Link, from /a, to /b.

<Link to='/b' params={_id}>blah blah</Link>

我试图传递的 id 是一个对象的属性,其中嵌套了 Link 组件.

The id I'm trying to pass is the property of an object in which the Link component is nested in.

我在另一个 StackOverflow 线程中发现了这个语法 params={}.我的代码编译没有中断,所以这可能意味着它有效?但是,我不确定如何在端点检索此传递的值.

I found this syntax params={} in another StackOverflow thread. My code compiled without breaking, so that probably means it worked? However, I'm not sure about how to retrieve this passed value at the endpoint.

任何帮助将不胜感激.

推荐答案

传递道具

您可以通过 state 对象将任意道具传递给路由:

You can pass arbitrary props to a route via the state object:

<Link to={{ pathname: '/route', state: { foo: 'bar'} }}>My route</Link>

然后你可以从你的组件中访问 state 对象:

Then you can access the state object from within your component:

const {foo} = props.location.state

console.log(foo) // "bar"

传递参数

配置你的路由路径以接受命名参数(:id):

Configure your route path to accept named parameters (:id):

<Route path='/route/:id' exact component={MyComponent} />

然后你可以在你的链接to中传递诸如ID之类的URL参数:

Then you can pass URL parameters such as IDs in your link to:

<Link to={`route/foo`}>My route</Link>

您可以通过 match 对象访问组件中的参数:

You can access the parameter within your component via the match object:

const {id} = props.match.params

console.log(id) // "foo"

来源

https://github.com/ReactTraining/react-router/issues/4036

这篇关于通过 React-Router v4 &lt;Link/&gt; 传递值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆