首页 > 解决方案 > 如何从子类中的componentdidmount将值返回到reactjs中的父类

问题描述

reactjs中如何从子类中的componentdidmount返回值到父类。单击 CARD 之一时,使用 PROMISE.all 从后端检索数据并保存在数据对象内部的子状态中。然后我需要一种方法将其返回给父类。当我阅读更多但没有输出时,我正在尝试不同的方式......

家长:

  render() {
    const { data} = this.state;
   
    callbackFunction = (data) => {
    this.setState({threeDaysData: data.getONE});
    this.setState({fourteenDaysData: data.getTWO});
  }

    return (
      <Grid container justify="center" alignItems="center" spacing={2}>
        {
          <Grid item xs={12} md={6} key={uj.userJourney}>
            <Child2 title={`CLICK 2`}
            threeDaysData
            fourteenDaysData
            // PASS threeDaysData and fourteenDaysData retrieved from to Child1 to Child2 ( on 2nd click )
          />
          </Grid>
        : 
          <Grid item xs={6}>
            <Child1
              title={`CLICK 1`}
              // RETRIEVE OBJECT VALUE FROM CHILD 1 IN THIS PARAM
              triggerParentUpdate={this.CallbackFunction(data)}
            />
          </Grid>
        }
      </Grid>
    );
  }
Child1:
  class Child1 extends Component {
  state = {
    3days: {
      threeDaysData: 'No Data',
    },
    14days: {
      fourteenDaysData: 'No Data',
    }
    data: {
      threeDaysData: 'No Data',
      fourteenDaysData: 'No Data'
    }
  };


  render() {
    const { title, data } = this.props;
    const { last3days, last14days } = this.state;
    return (
      <Card>
          <CardContent>
            <Grid container>
              {last3days !== undefined && last3days.calcThree !== undefined ? (
                last3days.calcThree
                  .map((element) => {
                    return (
                      <Grid item xs={3}>
                        ---
                      </Grid>
                    );
                  })
              )}

              {last14days !== undefined && last14days.calcThirty !== undefined ? (
                last14days.calcThirty
                  .map((element) => {
                    return (
                      <Grid item xs={3}>
                        ---
                      </Grid>
                    );
                  })
              )}
            </Grid>
          </CardContent>
      </Card>
    );
  }

  componentDidMount() {
    Promise.all([this.getData(3), this.getData(14)]).then((res) => {
      this.setState({
        3days: {
          threeDaysData: res[0].data,
        },
        14days: {
          fourteenDaysData: res[1].data,
        }
        data: {
          threeDaysData: res[0].data,
          fourteenDaysData: res[1].data
        }
      });
    });
  }
}```

标签: reactjs

解决方案


React 有一个“从父母到孩子”的流程,反之亦然。因此,为了将数据放入Parent组件中,您只需将数据移到componentDidMount那里,获取数据并通过 props 将其传递给所有子组件。


推荐阅读