我正在尝试将一些值作为 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/