Reactjs 如何从react中的子组件设置父组件的状态?
我在父组件中有一个状态,它有一个患者数组。我的Reactjs 如何从react中的子组件设置父组件的状态?,reactjs,parent-child,react-hooks,setstate,react-component,Reactjs,Parent Child,React Hooks,Setstate,React Component,我在父组件中有一个状态,它有一个患者数组。我的子组件4是一个倒计时组件(//倒计时组件为数组中的每个患者分别呈现倒计时),并且当倒计时开始时{ 如果(i==索引){ 返回{ 病人 位置信息:“”, 状态:“” }; } 返回病人; }), })); } render(){ 返回( 试着像这样调用函数 this.props.resetPatient(patient, index); 通过执行()=>this.props.resetPatient(patient,index);您只是声明了另一个必
子组件4
是一个倒计时组件
(//倒计时组件为数组中的每个患者分别呈现倒计时),并且当倒计时开始时{
如果(i==索引){
返回{
病人
位置信息:“”,
状态:“”
};
}
返回病人;
}),
}));
}
render(){
返回(
试着像这样调用函数
this.props.resetPatient(patient, index);
通过执行()=>this.props.resetPatient(patient,index);
您只是声明了另一个必须再次调用的函数,
你可以把它改成
(() => this.props.resetPatient(patient, index))();
但是这似乎是不必要的。试着像这样调用函数
this.props.resetPatient(patient, index);
通过执行()=>this.props.resetPatient(patient,index);
您只是声明了另一个必须再次调用的函数,
你可以把它改成
(() => this.props.resetPatient(patient, index))();
但是这似乎是不必要的。首先,当您已经在
resetPatient=(患者,索引)=>{…}使用箭头函数时,您不再需要this.resetPatient=this.resetPatient.bind(this);
第二,按如下方式传递回调:
<Child resetPatient= { this.resetPatient } />
希望它有帮助首先,当您已经在resetPatient=(患者,索引)=>{…}使用箭头函数时,您不再需要this.resetPatient=this.resetPatient.bind(this);
第二,按如下方式传递回调:
<Child resetPatient= { this.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 = (patient) => {
this.setState(prevState => ({
patients: prevState.patients.map(p => {
if (patient.id === p.id) {
return {
...p,
locationInfo: '',
status: ''
};
}
return p;
}),
}));
}
然后你可以打电话:
this.props.resetPatient(patient)
看起来您没有调用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 = (patient) => {
this.setState(prevState => ({
patients: prevState.patients.map(p => {
if (patient.id === p.id) {
return {
...p,
locationInfo: '',
status: ''
};
}
return p;
}),
}));
}
然后你可以打电话:
this.props.resetPatient(patient)
组件(4)中可能存在的重复项,索引从何而来?例如,您没有将其传递给父级。组件(4)中可能存在的重复项,索引从何而来?例如,您没有将其传递给父级。