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

Passing an object as prop in React-router Link

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

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

我的路线是

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

ProductList 组件 Link

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

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

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

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

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

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

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

product 路线应该与商店相连。 希望这有帮助。

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

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

那么您应该可以在 this.props.location.myCustomProps

中访问它们

你可以尝试像那样通过查询参数来实现,这很丑陋。

您也可以尝试用其他元素替换 Link,例如按钮和点击侦听器通过 browserHistory.push({ pathname:"/product/" + this.props.product.Id, state: this.props.product}) 和产品作为 state 属性.

进行位置更改