2017-02-12 67 views
0

我们正在创建我们的第一个React应用程序,以使用Shopify购买SDK创建电子商务网站。componentWillReceiveProps在点击链接组件后没有收到道具

眼下正确的数据是由产品详情成分,如果用户直接进入如下所示的路径被渲染:/product/SOMEPRODUCT_ID

然而,当在ProductCard组件的用户点击,对于clicked-数据产品不会在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> 
    ) 
    } 
} 

回答

0

生命周期方法componentWillReceiveProps在安装的组件接收新的道具之前被调用。所以,这个方法在组件被挂载时不会被调用。您需要在componentWillMount()生命周期方法中致电getCurrentProduct()

+0

非常感谢!这是很有意义的。 –

相关问题