【发布时间】:2020-06-17 13:35:35
【问题描述】:
我在 React 类组件中传递道具时遇到了一些问题。
<ProductCard allProducts={this.state.allProducts} />
在这里,我在父组件中使用 allProduct 属性调用 ProductCard 组件。我在 componentDidMount 中获取数据并使用 this.setState() 更新我的 state 中的 allProducts 但在 ProductCard 组件中,我将 allProducts prop 作为空数组获取,这是父组件 this.state.allProducts 中的初始值
但是如果我没记错的话,当我更新状态时,父组件应该重新渲染(确实如此),并且子组件的 prop 值也应该发生变化,但这不会发生。
父组件:
import React, { Component } from 'react'
import ProductCard from "../../Components/Products Card/ProductCard"
export default class SubCategory extends Component {
constructor () {
super()
this.state = {
allProducts:[]
}
}
componentDidMount = () => {
let productData = []
for(var i=0;i<10;i++){
productData.push({
productName:`Product ${i+1}`,
price:"9999"
})
}
this.setState({allProducts:productData})
}
render() {
return (
<>
<ProductCard allProducts={this.state.allProducts} name={this.state.name} />
</>
)
}
}
子组件:
import React, { Component } from 'react'
export default class ProductCard extends Component {
constructor(){
super()
this.state = {
allProducts:[]
}
}
componentDidMount= () => {
this.setState({allProducts:this.props.allProducts})
}
render() {
return (
<>
...
</>
)
}
}
任何帮助将不胜感激。谢谢!
【问题讨论】:
-
好吧,把父组件的代码也贴一下。
-
请发minimal reproducible example。最好是Stack Snippet。根本无法根据此处显示的内容来诊断此问题。
-
在
ProductCard里面,你在哪里检查allProducts的值?也添加它。 -
我需要获取 prop 值并将其设置为
ProductCard状态。但我需要更改父组件中的道具。我在ProductCard的 componentDidMount 中设置状态。 -
@SuryaMahla - 添加
ProductCard的代码。
标签: javascript arrays reactjs