【发布时间】:2017-02-12 05:41:36
【问题描述】:
我们正在创建我们的第一个 React 应用,以使用 Shopify Buy SDK 创建一个电子商务网站。
现在,如果用户直接进入如下路径,则 ProductDetail 组件会呈现正确的数据:/product/SOMEPRODUCT_ID
但是,当用户单击 ProductCard 组件时,单击产品的数据不会呈现在 ProductDetail 组件中。
为了确定与 ProductDetail 组件关联的正确数据,我们创建了在 componentWillReceiveProps 生命周期挂钩期间调用的 getCurrentProduct 方法。 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>
)
}
}
【问题讨论】:
标签: javascript reactjs react-router url-routing