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

查看:70
本文介绍了通过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.这样的<Link to='/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中传递URL参数,例如ID:

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天全站免登陆