簡體   English   中英

如何在反應中從子組件設置父組件的 state?

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

我在父組件中有一個 state,它有一組患者。 我的Child Component 4是一個Countdown component (// 倒計時組件為數組中的每個患者單獨呈現倒計時),當倒計時到達 <=0 時,我想將患者的locationInfo & status值重置為空字符串患者陣列。 在我的父組件中,我有resetPatient function 映射到patient array ,並且應該將具有 <=0 計數器的患者的值(locationInfo & status)設置為空字符串。 resetPatient function 作為道具傳遞給我的倒計時組件 (4)。 在 Countdown 組件中,當計數器達到 <=0 時,我調用this.props.resetPatient function。 但是,這對我不起作用。 父組件上的 state 不會改變。

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
        }
    }

如何在反應中從子組件中設置父組件的 state。

首先,您不再需要this.resetPatient = this.resetPatient.bind(this); 當您已經在resetPatient = (patient, index) => {...}處使用箭頭 function

其次,像這樣傳遞你的回調:

<Child resetPatient= { this.resetPatient } />

然后在 child 作為道具訪問它:

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

希望能幫助到你

看起來您沒有調用resetPatient ,並且無論如何該index都沒有在 scope 中定義。

我會為您的患者 object 添加一個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)

嘗試像這樣調用 function

this.props.resetPatient(patient, index);

通過() => this.props.resetPatient(patient, index); 您只是在聲明另一個 function ,您必須再次調用它,您可以將其更改為

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

但這似乎是不必要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM