在 React-router Link 中将对象作为道具传递

Posted

技术标签:

【中文标题】在 React-router Link 中将对象作为道具传递【英文标题】:Passing an object as prop in React-router Link 【发布时间】:2018-08-03 14:32:31 【问题描述】:

我正在获取ProductList 中的产品列表,其中我需要将选定的产品对象传递给Product

目前,我正在尝试将 id 作为路由参数传递并再次获取产品对象。但我想将整个产品对象从ProductList 发送到Product

我的路线是

<Route path=joinPath(["/product", ":id?"]) component=Product />

ProductList组件链接

<Link to="/product/" + this.props.product.Id >this.props.product.Name </Link>

如何将产品对象作为道具传递给Product

下面的在 Typescript 中抛出错误,说 Link Type 上不存在以下属性。

<Link to="/product/" + this.props.product.Id params=product>Name</Link>

我尝试了以下问题,但似乎都没有我的问题。

Pass props in Link react-router &lt;--- this is similar to my issue, but answer doesn't work for react-router v4 react-router - pass props to handler component React: passing in properties

【问题讨论】:

【参考方案1】:

Link 的“to”属性可以接受一个对象,因此您可以像这样传递您的道具:

<Link to=
     
        pathname: "/product/" + this.props.product.Id,
        myCustomProps: product
    
>
    Name
</Link>

那么你应该可以在this.props.location.myCustomProps访问它们

【讨论】:

是的,我现在能够以同样的方式做到这一点。虽然我认为从redux 获取会更整洁。【参考方案2】:

我建议使用redux 来检索数据。当您导航到产品路线时,您可以通过调度一些操作来获取 product 详细信息。

componentDidMount() 
    let productId = this.props.match.params.Id;
    this.props.actions.getProduct(productId);

product 路由应该与 store 相连。 希望这会有所帮助。

【讨论】:

是的,我也是这么想的。但是是否可以将一个对象作为 prop 传递给另一个组件 tru Link【参考方案3】:

你可以尝试像Pass object through Link in react router那样通过查询参数来实现,相当难看。

您也可以尝试将 Link 替换为其他元素,例如按钮并在点击侦听器中通过browserHistory.push( pathname:"/product/" + this.props.product.Id, state: this.props.product) 和产品作为state 属性更改位置。

【讨论】:

browserHistory 不在React-router-v4 是的,现在它是一个单独的模块,你需要包含它reacttraining.com/react-router/web/api/Router

以上是关于在 React-router Link 中将对象作为道具传递的主要内容,如果未能解决你的问题,请参考以下文章

在文本中将 <a> 替换为 React <Link>

React-Router 介绍及使用

实现react-router中的BrowserRouter、Route、Link

[react-router] React-Router的<Link>标签和<a>标签有什么区别

react-router:如果 <Link> 处于活动状态,如何禁用它?

强制 React-Router <Link> 加载页面,即使我们已经在该页面上