简体   繁体   English

道具未传递到React组件

[英]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: {}. 看来当我console.log(JSON.stringify(props))时,结果是:{}。

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. 当您执行本质上是异步的API调用时,响应可能会在子组件已呈现后返回。

Also best possible way to perform API call, is to use componentDidMount lifecycle. 执行API调用的最佳方法也是使用componentDidMount生命周期。 componentWillMount has been deprecated and not advised to use for asynchronous operations(ie Network calls). componentWillMount已被弃用,不建议用于异步操作(即网络调用)。

So constructor() gets called only once on any component. 因此, constructor()在任何组件上仅被调用一次。 The lifecycle you need is componentDidUpdate which always checks for new/updated props and it's state . 您需要的生命周期是componentDidUpdate ,它总是检查新的/更新的props及其state

This will look like in Product Component: 外观类似于Product组件:

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,
        })
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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