单击链接组件

时间:2017-02-12 05:41:36

标签: javascript reactjs react-router url-routing

我们正在创建第一个使用Shopify Buy SDK创建电子商务网站的React应用程序。

现在,如果用户直接转到如下所示的路径,则ProductDetail组件将呈现正确的数据:/product/SOMEPRODUCT_ID

但是,当用户单击ProductCard组件时,单击的产品的数据不会在ProductDetail组件中呈现。

为了确定与ProductDetail组件关联的正确数据,我们创建了在getCurrentProduct生命周期钩子期间调用的componentWillReceiveProps方法。 ProductCard和ProductDetail组件都可以访问this.props.products,这是所有产品的数组。

当用户点击ProductCard组件的链接时,是否有任何生命周期钩子允许我们从this.props获取产品?

以下是ProductDetail组件。

import React, { Component } from 'react';

class ProductDetail extends Component {
  constructor() {

    super();

    this.state = {
      product: {}
    };

    this.getCurrentProduct = this.getCurrentProduct.bind(this);
  }

  componentWillReceiveProps(nextProps) {

    this.getCurrentProduct(nextProps.products);
  }

  getCurrentProduct(products) {

    const slug = this.context.match.parent.params.id;

    const product = products.filter(product => {
      return product.handle === slug;
    })[0];

    this.setState({ product });
  }

  render() {
    return (
      <main className="view view--home">
        {this.state.product.title}
      </main>
    );
  }
}

ProductDetail.contextTypes = {
  match: React.PropTypes.object
}

export default ProductDetail;

以下是ProductCard组件。

import React, { Component } from 'react';
import { Link } from 'react-router';

class ProductCard extends Component {
  render() {
    const { details } = this.props;
    return (
      <figure className="product-card">
        <Link to={`/product/${this.props.id}`}>
          <img src={details.images[0].src} alt={details.title} className="product-card__thumbnail" />
        </Link>
        <Link to={`/product/${this.props.id}`}>
          <figcaption className="product-card__body">
            <h3 className="product-card__title">{details.title}</h3>
            <span className="product-card__price">{details.rendered_price}</span>
          </figcaption>
        </Link>
      </figure>
    )
  }
}

1 个答案:

答案 0 :(得分:0)

在安装的组件接收新道具之前调用生命周期方法componentWillReceiveProps。因此,在安装组件时不会调用此方法。在这里,您需要在getCurrentProduct()生命周期方法中调用componentWillMount()

相关问题