简体   繁体   English

如何将额外的道具传递到新页面 <Link> 用React-Router?

[英]How to pass extra props to new page through <Link> with React-Router?

I have a new page that's rendered and accessed through a <Link> that's being passed a bookName and bookEdition . 我有一个新页面,该页面通过<Link>呈现和访问,正在传递给bookNamebookEdition This works fine, great. 这很好,很好。

<Router history={browserHistory}>
    <Route path="/" component={App}/>
    <Route path="/book/:bookName/:bookEdition" component={Book}/>
</Router>

<Link to={"/book/ReactJS For Dummies/1st Edition"}><p>Link here</p></Link>

However, I want to pass additional context data about the book and the search results it was found in to the new page, through a prop or something. 但是,我想通过道具或其他方式将有关该书的其他上下文数据以及在该书中找到的搜索结果传递到新页面。 I've tried something like this to no avail: 我已经尝试过类似的事情,但没有成功:

<Link to={"/book/ReactJS For Dummies/1st Edition"} params={{hits:hit}}><p>Link here</p></Link>

I know I can add additional data to the <Route> component, as hits={hit} , but that's out of scope for the data that I need to pass through. 我知道我可以将其他数据添加到<Route>组件中,如hits={hit} ,但这超出了我需要传递的数据的范围。 It needs to be passed through where the <Link> exists. 它必须通过<Link>所在的地方传递。

The router in your app is not designed for passing such data. 您应用中的路由器不适用于传递此类数据。 My experience shows me that this is a bad approach. 我的经验告诉我,这是一种不好的方法。 If you are app needs to transfer information from one page to another the URL is definitely not a good place for that. 如果您的应用程序需要将信息从一页转移到另一页,则URL绝对不是一个好地方。 It simply doesn't scale. 它根本无法扩展。 I guess you are using flux (or redux) so manage that use case in your app state. 我猜您正在使用flux(或redux),因此请在您的应用程序状态下管理该用例。 Dispatch a dedicated action and keep that data so you can consume it later. 调度专用操作并保留该数据,以便以后使用。

You can pass those additional props as query parameters. 您可以将这些其他道具作为查询参数传递。

<Link to={"/book/ReactJS For Dummies/1st Edition"} query={{hits: hits}}><p>Link here</p></Link>

You can then access these values inside your Book component from this.props.location.query 然后,您可以从this.props.location.query访问Book组件内的这些值。

Update 更新

Since passing query params as query prop has been deprecated in React-Router v2, you can instead pass it like this: 由于在React-Router v2中已弃用将查询参数作为query道具传递,因此您可以这样传递它:

<Link to={{ pathname: "/book/ReactJS For Dummies/1st Edition", query: {hits: hits} }}><p>Link here</p></Link>

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM