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

How to set state of parent component from a child component in react?

我在父组件中有一个状态,它有一个患者数组。我的 Child Component 4 是一个 Countdown component(// 倒计时组件为数组中的每个患者单独呈现倒计时)并且当倒计时达到 <=0 时,我想重置患者的 locationInfo & status患者数组中的值为空字符串。在我的父组件中,我有 resetPatient 映射到 patient array 的函数,并且应该将具有 <=0 计数器的患者的值 (locationInfo & status) 设置为空字符串。 resetPatient 函数作为道具向下传递到我的倒计时组件 (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中从子组件设置父组件的状态。

尝试像这样调用函数

this.props.resetPatient(patient, index);

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

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

但这似乎是不必要的。

首先,当您已经在 resetPatient = (patient, index) => {...}

处使用箭头函数时,您不再需要 this.resetPatient = this.resetPatient.bind(this);

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

<Child resetPatient= { this.resetPatient } />

然后在 child 中访问它作为 props :

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

希望对您有所帮助

看起来您没有调用 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)