如何在反应中从子组件设置父组件的状态?

时间:2019-09-23 10:31:14

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

我在“父组件”中有一个状态,该状态包含一系列患者。我的Child Component 4Countdown component(//倒数组件为数组中的每个患者分别进行倒数),当倒数达到<= 0时,我想重置患者的locationInfo & status值是患者数组中的空字符串。在我的父组件中,我具有resetPatient函数,该函数映射到patient array上,并应设置<= 0的患者的值(locationInfo & status)等于空字符串。 resetPatient函数作为道具向下传递给我的Countdown component(4)。在倒数组件中,当计数器变为<= 0时,我调用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中从子组件设置父组件的状态。

3 个答案:

答案 0 :(得分:1)

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

第二,像这样传递您的回调:

<Child resetPatient= { this.resetPatient } />

然后作为道具在子级中访问它:

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

希望有帮助

答案 1 :(得分: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 :(得分:0)

尝试像这样调用函数

this.props.resetPatient(patient, index);

通过执行() => this.props.resetPatient(patient, index);,您只是在声明另一个必须再次调用的函数, 您可以将其更改为

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

但这似乎是不必要的。

相关问题