Passing an object as prop in React-router Link

本秂侑毒 提交于 2019-12-05 06:33:35

问题


I'm getting the list of products in ProductList, in which, I need to pass the selected product object to Product.

Currently, I'm trying pass the id as a route param and get the product object again. But I want to send the entire product object from ProductList to 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?

the below one throws error in Typescript saying the following property does not exist on Link Type.

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

I tried the following questions, but none seems to have my issues.

  • Pass props in Link react-router <--- 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:


The "to" property of Link can accept an object so you can pass your props like this :

<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




回答2:


I would suggest using redux for retrieving the data. When you navigate to product route you can get the product details by dispatching some action.

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

The product route should be connected with the the store. Hope this helps.




回答3:


You can try to do it through query params as in Pass object through Link in react router, which is quite ugly.

Also you can try to replace Link with some other element, e.g. 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.



来源:https://stackoverflow.com/questions/48949479/passing-an-object-as-prop-in-react-router-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!