javascript - Props 未传递给 React 组件

标签 javascript reactjs jsx

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

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

关于javascript - Props 未传递给 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57414315/

相关文章:

javascript - ionic 框架 typescript : Callback function is not able to access `this` variables

node.js - Node Express 未提供 Gzip 文件

php - 如何在加载 js 之前使用 url 中的值设置 cookie

javascript - 学习者问题 : How to conditionally set wrapper for this particular code. React/SPFX

javascript - 使用Javascript/Jquery播放音频文件

javascript - 未捕获的类型错误 : Cannot call method 'push' undefined in jquery-1. 5.1.min.js

javascript - 如何检测网站是否无法通过 iframe 嵌入?

reactjs - 使用react-slick更改当前幻灯片

css - React jsx &lt;input/> 组件的条件样式

ReactJs:this.props.children 的 PropType 应该是什么?