【问题标题】:How to set state of parent component from a child component in react?如何在反应中从子组件设置父组件的状态?
【发布时间】:2019-09-23 10:31:14
【问题描述】:

我在父组件中有一个包含患者数组的状态。我的Child Component 4 是一个Countdown component(// 倒计时组件为数组中的每个患者单独呈现倒计时),当倒计时到达locationInfo & status 值重置为空字符串患者阵列。在我的父组件中,我有 resetPatient 函数映射到 patient array 并且应该将具有 (locationInfo & status) 设置为空字符串。 resetPatient 函数作为道具传递给我的 Countdown 组件 (4)。在 Countdown 组件中,当计数器达到 this.props.resetPatient 函数。但是,这对我不起作用。父组件的状态不会改变。

Parent Component - Child Component 1 - Child Component 2 - Child Component 3 - Child Component 4

Parent component 

export default class ObservationWorkflow extends React.Component {


    constructor(props) {
        super(props);
       this.state = {

         patients = [
           { room: "1", name: 'John', locationInfo: 'TV', status: 'Awake'},
           { room: "2", name: 'Shawn, locationInfo: 'Toilet', status: 'Awake'},
           { room: "3", name: 'Gereth, locationInfo: 'Garden', status: 'Awake'}
          ]
         }
       this.resetPatient = this.resetPatient.bind(this);

 }


    resetPatient = (patient, index) => {

        this.setState(prevState => ({

            patients: prevState.patients.map((patient, i) => {
                if (i === index) {
                    return {
                        ...patient,
                        locationInfo: '', 
                        status: ''
                    };
                }
                return patient;
            }),
        }));
    }

   render() {
      return (
    <Child component(1)={this.resetPatient} // then child component 2 passes it down as props to 3 then 4. 
     )
   }
}

Countdown component(4)// countdown component renders individually countdown for each patient in the array. 

 export default class ObservationCountDown extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            obsTimeleft: undefined
        };

        this.countDown = this.countDown.bind(this);
        this.startCountdown = this.startCountdown.bind(this);
        this.countDownInterval = null;
    }

    countDown() {

        const { obsTakenTime, patient, index } = this.props; 
        const nextDueTimeForObs = moment(obsTakenTime).add(10, 'minutes'); 

        const nextObservationTime = nextDueTimeForObs.subtract(moment.now()).format('mm');

        if (obsTakenTime) {
            this.setState({ obsTimeleft: nextObservationTime + ' mins' });
        }
        if (Number(nextObservationTime) <= 1) {
            this.props.disablePatientUpdate();
        }
        if (Number(nextObservationTime) <= 0) {
            this.setState({ obsTimeleft: 'Overdue' });
            this.props.enablePatientUpdate();
            clearInterval(this.countDownInterval);

            () => this.props.resetPatient(patient, index); // here i call the function as call back
        }
    }

如何在 react 中从子组件中设置父组件的状态。

【问题讨论】:

标签: reactjs parent-child react-hooks setstate react-component


【解决方案1】:

您似乎没有调用resetPatient,并且无论如何都没有在该范围内定义index

我会在您的患者对象中添加一个id,并使用它来确定需要重置的对象:

 patients = [
       { id:1, room: "1", name: 'John', locationInfo: 'TV', status: 'Awake'},
       { id:2, room: "2", name: 'Shawn, locationInfo: 'Toilet', status: 'Awake'},
       { id:3, room: ... }]

你的resetPatient 会变成:

 resetPatient = (patient) => {

    this.setState(prevState => ({

        patients: prevState.patients.map(p => {
            if (patient.id === p.id) {
                return {
                    ...p,
                    locationInfo: '', 
                    status: ''
                };
            }
            return p;
        }),
    }));
}

然后你可以打电话:

   this.props.resetPatient(patient)

【讨论】:

    【解决方案2】:

    首先,当您已经在resetPatient = (patient, index) =&gt; {...} 使用箭头功能时,您不再需要this.resetPatient = this.resetPatient.bind(this);

    其次,像这样传递你的回调:

    <Child resetPatient= { this.resetPatient } />
    

    然后在 child 作为 props 访问它:

     this.props.resetPatient(..., ...)
    

    希望对你有帮助

    【讨论】:

      【解决方案3】:

      尝试像这样调用函数

      this.props.resetPatient(patient, index);
      

      通过() =&gt; this.props.resetPatient(patient, index); 你只是声明了另一个你必须再次调用的函数, 你可以把它改成

      (() => this.props.resetPatient(patient, index))();
      

      但这似乎是不必要的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-14
        • 2018-09-08
        • 1970-01-01
        • 2021-01-23
        • 2021-06-27
        相关资源
        最近更新 更多