Мы создаем наше первое приложение React для создания сайта электронной коммерции с помощью Shoppect Buy SDK.componentWillReceiveProps не получает реквизиты после нажатия на компонент Link
Щас правильные данные визуализируется компонентом ProductDetail, если пользователь переходит непосредственно к пути, как следующее: /product/SOMEPRODUCT_ID
Однако, когда пользователь нажимает на компонент ProductCard, данные для clicked- на продукт не отображается в компоненте ProductDetail.
Чтобы определить правильные данные, связанные с компонентом ProductDetail, мы создали метод getCurrentProduct
, который вызывается во время цикла жизненного цикла componentWillReceiveProps
. У компонентов 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>
)
}
}
спасибо! Это тонна смысла. –