【发布时间】: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 中从子组件中设置父组件的状态。
【问题讨论】:
-
在你的组件(4)中,索引来自哪里?例如,你没有把它交给你的父母。
标签: reactjs parent-child react-hooks setstate react-component