简体   繁体   English

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

[英]Passing an object as prop in React-router Link

I'm getting the list of products in ProductList , in which, I need to pass the selected product object to Product .我正在获取ProductList中的产品ProductList ,其中,我需要将选定的产品对象传递给Product

Currently, I'm trying pass the id as a route param and get the product object again.目前,我正在尝试将id作为路由参数传递并再次获取产品对象。 But I want to send the entire product object from ProductList to Product .但我想将整个产品对象从ProductList发送到Product

My Route is我的路线是

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

ProductList component Link产品列表组件链接

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

How to pass product object to Product as a prop?如何将产品对象作为道具传递给Product

the below one throws error in Typescript saying the following property does not exist on Link Type.下面的一个在 Typescript 中抛出错误,说Link类型上不存在以下属性。

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

I tried the following questions, but none seems to have my issues.我尝试了以下问题,但似乎都没有我的问题。

The " to " property of Link can accept an object so you can pass your props like this : Link的“ to ”属性可以接受一个对象,因此您可以像这样传递道具:

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

Then you should be able to access them in this.props.location.myCustomProps然后你应该可以在this.props.location.myCustomProps访问它们

I would suggest using redux for retrieving the data.我建议使用redux来检索数据。 When you navigate to product route you can get the product details by dispatching some action.当您导航到产品路线时,您可以通过调度一些操作来获取product详细信息。

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

The product route should be connected with the the store. product路线应与门店相连。 Hope this helps.希望这会有所帮助。

You can try to do it through query params as in Pass object through Link in react router , which is quite ugly.您可以尝试通过查询参数来完成,如通过 React router 中的链接传递对象,这非常难看。

Also you can try to replace Link with some other element, eg button and in click listener do location change via browserHistory.push({ pathname:"/product/" + this.props.product.Id, state: this.props.product}) and and product as state property.您也可以尝试用其他一些元素替换链接,例如按钮,并在单击侦听器中通过browserHistory.push({ pathname:"/product/" + this.props.product.Id, state: this.props.product}) and 和 product 作为state属性。

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

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