【问题标题】:Updating child props when we change them in Parent Component当我们在父组件中更改子道具时更新它们
【发布时间】: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


【解决方案1】:

在您的子组件中尝试像这样更改您的构造函数:

constructor(props) {
    super(props)
    this.state = {
        allProducts:[]
    }
}

更新:

  render() {
    return (
      <>
        {this.state.allProducts.length > 0 ? (
          <ProductCard
            allProducts={this.state.allProducts}
            name={this.state.name}
          />
        ) : null}
      </>
    );
  }

【讨论】:

  • 我试过了,它仍然给出空数组。我想我需要检查子组件中的道具是否更新,然后用新的更新道具重新设置状态。我的想法是否正确?
  • 或者当你的数组有一些产品时你只能渲染ProductCard组件。
  • 是的,这种方法也可以。当我的道具发生变化时,我通过比较旧道具和新道具然后将更新后的道具存储在子组件的状态中来检查我的子组件,从而使其工作。
  • @SuryaMahla - 好的,您可以在问题解决后将此标记为答案。
猜你喜欢
  • 2018-09-28
  • 1970-01-01
  • 1970-01-01
  • 2018-07-02
  • 1970-01-01
  • 2019-08-27
  • 1970-01-01
  • 1970-01-01
  • 2020-02-07
相关资源
最近更新 更多