【问题标题】:Display item details after clicking Link in React Router在 React Router 中单击链接后显示项目详细信息
【发布时间】:2017-06-08 18:44:39
【问题描述】:

我使用路由器进行路由。有一个产品列表,当单击产品时,应显示该产品的详细信息页面(产品名称,产品价格)。我尝试在查询中传递产品对象,但它不是那样工作的。

这是我的代码

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 未定义吗?
  • 我得到 [object 对象]。我看不到对象内部的内容。
  • 试试console.log('product', this.props.location.query.query)
  • 我已附上图片

标签: javascript html reactjs ecmascript-6 react-router


【解决方案1】:

他们query 的位置描述符对象将被转换为查询字符串。您可以使用位置描述符的state property 在视图之间传递状态。

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

然后,在您的产品组件中,您可以检查this.props.location.state 以获取相关数据。这样做的缺点是直接导航到相同 URL 的用户将无法使用 state

【讨论】:

  • 为了解决缺点,是否只有localstorage选项?
  • 这完全取决于您的数据来自哪里。除了将内容保存在 localStorage 中之外,您还可以检查 location.state 是否存在,如果不存在,则对数据发出 AJAX 请求。
【解决方案2】:

我建议您将产品列表作为props 传递给ProductView,然后检索带有id 的产品。这样,当用户直接导航到产品时,就没有缺点了。

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>
    );
  }
}

【讨论】:

  • 首先我必须使用 mapStateToProps 获取产品的状态并使用 find 函数找到与查询中传递的 id 匹配的产品,对吧?
  • 我得到 this.props.products.find 不是函数错误
  • 是的,您必须先获取产品(我不知道 mapStateToProps,我从未使用过 Redux)。您可以在获取产品时显示加载(请参阅我的编辑)。
  • 使用空数组 (products = []) 初始化产品,然后获取产品。这种方式this.props.products 永远不会未定义。
  • 很高兴它对您有所帮助。 :)
猜你喜欢
  • 2019-11-09
  • 2018-07-31
  • 1970-01-01
  • 2013-02-11
  • 2020-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多