【发布时间】:2020-11-19 20:04:02
【问题描述】:
我正在尝试根据用户在两个字段中的输入来更新我的状态数据,但我不确定我是否以正确的方式进行。
父组件Encounter.js 保持状态,我将尝试限制我在此处添加的代码量,这样我的问题就很清楚了。所以在ComponentDidUpdate 我用一个对象设置状态并创建一个更新函数来更新状态。我将状态中的两个值与更新状态函数一起传递给另一个组件PatientInfo:
componentDidUpdate(prevProps) {
if (this.props.details && this.props.details.medicalIntake && !prevProps.details.medicalIntake) {
this.setState({ pertinentMedications: {
covid19Protocol: this.props.details.medicalIntake.pertinentMedications.covid19Protocol,
note: "" || this.props.details.medicalIntake.pertinentMedications.notes
}})
}
}
pertinentMedicationsChange = (newValues) => {
this.props.setIdleTime();
this.props.setState({pertinentMedications: newValues});
}
return (
<PatientInfo
covid19Protocol={this.state.pertinentMedications.covid19Protocol}
pertinentMedicationsNote={this.state.pertinentMedications.note}
pertinentMedicationsChange={this.pertinentMedicationsChange}
/>
)
PatientInfo.js 只是将道具向下传递。
<PertinentMedications
covid19Protocol={this.props.covid19Protocol}
pertinentMedicationsNote={this.props.pertinentMdicationsNote}
pertinentMedicationsChange={this.props.pertinentMedicationsChange}
/>
PertinentMedications.js 是收集用户输入的地方:
const PertinentMedications = ({
covid19Protocol,
pertinentMedicationsNote,
pertinentMedicationsChange
}) => {
const [isChecked, setIsChecked] = useState(covid19Protocol)
const onClick = (field, value) => {
setIsChecked(!isChecked)
pertinentMedicationsChange( {[field]: value})
}
const onNoteChange = (field, value) => {
pertinentMedicationsChange( {[field]: value})
}
return(
<ContentBlock title="Pertinent Medications and Supplements">
<CheckToggle onChange={() => onClick("covid19Protocol", !covid19Protocol)} checked={isChecked}>
<p>Patient has been receiving the standard supportive care and supplements as per COVID-19 protocol.</p>
</CheckToggle>
<Input
type="textarea"
name="pertinentMedications"
onChange={e => onNoteChange("notes" ,e.target.value)}
value={pertinentMedicationsNote}
/>
</ContentBlock>
)
}
export default PertinentMedications;
我真正的问题在于pertinentMedicationsChange 函数,因为我不确定如何获取从PertinentMedications 组件获取的数据并将其格式化以放置在状态中。首先,我不确定我是否可以像我尝试使用这两个将数据发送到此函数以更改状态的独立字段一样更新状态?如果可能的话,我不确定在调用 setState 时如何正确设置键值对。有人可以帮忙吗?
【问题讨论】: