简体   繁体   中英

Props not being passed to React component

I'm trying to pass some values as props to one component that I have (Product).

It seems when I console.log(JSON.stringify(props)), the result is: {}.

What can i possibly may be doing wrong?

export default class ProductList extends Component {
    constructor(props) {
        super(props);

        this.state = {
            productList: [],
        }
    };

    componentWillMount() {
        fetch('http://localhost:9000/api/products/getSixProducts?pageNumber=1')
            .then((res) => res.json())
            .then(((products) => products.map((product, index) => {
                this.state.productList.push(
                    <Product
                        key={index}
                        id={product._id}
                        brandId={product.brandId}
                        image={product.image}
                        price={product.price}
                        priceDiscounted={product.priceDiscounted}
                        subtitle={product.subtitle}
                    />)
            })))

            .catch(this.setState({ productList: [-1] }))
...

This is my Product constructor:

...
    constructor(props) {
        super(props);
        this.state = {
            id: props.id,
            brandId: props.brandId,
            subtitle: props.subtitle,
            price: props.price,
            priceDiscounted: props.priceDiscounted,
            image: { productImage }
        }
        console.log(JSON.stringify(props));
    }
...

As you are performing API call which is asynchronous in nature, the response may return after the child component might have been rendered.

Also best possible way to perform API call, is to use componentDidMount lifecycle. componentWillMount has been deprecated and not advised to use for asynchronous operations(ie Network calls).

So constructor() gets called only once on any component. The lifecycle you need is componentDidUpdate which always checks for new/updated props and it's state .

This will look like in Product Component:

componentDidUpdate(prevProps, prevState) {
    if (prevProps !== this.props) {
     console.log('updated Props',this.props); // You can check this.props will change if they are updated
        this.setState({
            id: this.props.id,
            brandId: this.props.brandId,
            subtitle: this.props.subtitle,
            price: this.props.price,
            priceDiscounted: this.props.priceDiscounted,
        })
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM