首页 文章

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

提问于
浏览
1

我在 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>

我尝试了以下问题,但似乎没有一个问题 .

3 回答

  • 1

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

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

    然后你应该能够在 this.props.location.myCustomProps 中访问它们

  • 0

    您可以尝试通过Pass object through Link in react router中的查询参数来执行此操作,这非常难看 .

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

  • 3

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

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

    product 路由应与商店连接 . 希望这可以帮助 .

相关问题