在React Router中单击链接后显示项目详细信息 [英] Display item details after clicking Link in React Router

查看:164
本文介绍了在React Router中单击链接后显示项目详细信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已使用路由器进行路由.这里有一个产品列表,单击产品后,应显示该产品的详细信息页面(product.name,product.price).我尝试在查询中传递产品对象,但这种方式无法正常工作.

I have used router for routing. There is a list of product and when a product is clicked, a detail page of that product should be shown(product.name, product.price). I tried passing product object in query but it is not working that way.

这是我的代码

productGrid.js

const product = _.map(products, (product) =>
            <Col xs={12} md={4} key={product.id} className="products">
              <div className="product">
                <Link to={{pathname: `product/${product.name}`, query: { query: product }}}>
                  <img src={product.image} className="img-responsive" />
                </Link>
                <span className="pull-left product-name">{product.name}</span>
                <span className="pull-right price">${product.price}</span>
              </div>
            </Col>
          );

product-view.js

class ProductView extends React.Component {
  render() {
    console.log('product', this.props.location.query);
    return (
      <div>Product View</div>
    );
  }
}

this.props.location.query控制台

this.props.location.query consoles

推荐答案

我建议您将产品列表作为props传递给ProductView,然后检索带有id的产品.这样,当用户直接导航到产品时就没有任何不利之处.

I would suggest you to pass the list of products as props to ProductView then to retrieve the product with its id. This way there is no downside when a user navigates directly to the product.

productGrid.js

<Link to={{pathname: `product/${product.name}`, query: { id: product.id }}}>

product-view.js

class ProductView extends React.Component {
  render() {
    const { products, location } = this.props;

    if (!products.length || !location) {
        return (<div>Loading...</div>);
    }

    const product = products.find(p => p.id == location.query.id);

    return product ? (
      <div>
        <h1>{product.name}</h1>
        <img src={product.image} />
        <p>{product.price}</p>
      </div>
    ) : (
      <div>Error: Product doesn't exist</div>
    );
  }
}

这篇关于在React Router中单击链接后显示项目详细信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆