繁体   English   中英

道具未传递到React组件

[英]Props not being passed to React component

我正在尝试将一些值作为道具传递给我拥有的一个组件(产品)。

看来当我console.log(JSON.stringify(props))时,结果是:{}。

我可能做错了什么?

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] }))
...

这是我的产品构造函数:

...
    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));
    }
...

当您执行本质上是异步的API调用时,响应可能会在子组件已呈现后返回。

执行API调用的最佳方法也是使用componentDidMount生命周期。 componentWillMount已被弃用,不建议用于异步操作(即网络调用)。

因此, constructor()在任何组件上仅被调用一次。 您需要的生命周期是componentDidUpdate ,它总是检查新的/更新的props及其state

外观类似于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