我们正在创建第一个使用Shopify Buy创建电子商务站点的React应用程序。
现在,如果用户直接进入如下路径,则ProductDetail组件将呈现正确的数据:/product/SOMEPRODUCT_ID
但是,当用户单击ProductCard组件时,单击的产品的数据不会在ProductDetail组件中呈现。
为了确定与ProductDetail组件关联的正确数据,我们创建了在componentWillReceiveProps
生命周期挂钩期间调用的getCurrentProduct
方法。ProductCard和ProductDetail组件都可以访问this.props.products
,这是所有产品的数组。
当用户单击来自this.props
组件的链接时,是否有任何生命周期挂钩可以让我们从ProductCard获得产品?
下面是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>
)
}
}
发布于 2017-02-12 00:49:17
在挂载组件接收新道具之前调用生命周期方法componentWillReceiveProps
。因此,在安装组件时不会调用此方法。在这里,您需要在getCurrentProduct()
生命周期方法中调用componentWillMount()
。
https://stackoverflow.com/questions/42184588
复制