如何在react-calendar中展示数据库返回的DateTime值
解决react-calendar更新时无法展示DateTime的问题
核心问题是react-calendar的value属性需要接收Date对象,而你当前把状态存成了格式化后的字符串(比如"January 1st 2024"),组件无法识别这种格式,导致渲染报错。
修复步骤:
状态存Date对象而非格式化字符串
初始化DateOfBirth状态时,直接把后端返回的日期字符串转换成Date对象,不要先格式化。同时处理后端返回空值的情况,避免报错。提交时再转换为后端需要的格式
如果后端需要特定格式的日期字符串,在提交表单的时候再做转换,不要把格式化后的值存在状态里。
修改后的代码示例:
PatientForm组件:
export function PatientForm(props) { const [PatientId, setPatientId] = useState(props.patient.patientId); const [FirstName, setFirstName] = useState(props.patient.firstName); const [LastName, setLastName] = useState(props.patient.lastName); const dateReceived = props.patient.dateOfBirth; // 初始化:把后端日期字符串转成Date对象,处理空值 const initialDateOfBirth = dateReceived ? new Date(dateReceived) : null; const [DateOfBirth, setDateOfBirth] = useState(initialDateOfBirth); const [Gender, setGender] = useState(props.patient.gender); const [DoctorId, setDoctorId] = useState(props.patient.doctorId); const handleSubmit = (e) => { e.preventDefault(); // 提交时转换为后端需要的格式(比如ISO字符串或指定格式) const submitDate = DateOfBirth ? moment(DateOfBirth).format('YYYY-MM-DD') : null; props.submit({ PatientId, FirstName, LastName, DateOfBirth: submitDate, Gender, DoctorId }); } // react-calendar组件的正确写法 return ( <form onSubmit={handleSubmit}> {/* 其他表单字段 */} <Calendar onChange={setDateOfBirth} value={DateOfBirth} /> <button type="submit">提交</button> </form> ) }
额外注意点:
- 后端返回的日期字符串如果是ISO格式(比如
"2024-01-01T00:00:00.000Z"),new Date()可以直接解析,moment也能处理。 - 如果后端返回的日期格式比较特殊,你可以用moment的
moment(dateReceived, '目标格式')来解析,再转成Date对象:moment(dateReceived, 'YYYY/MM/DD').toDate()。 - 确保
UpdatePatient组件中patient加载完成后再渲染PatientForm,避免props.patient.dateOfBirth为undefined导致的解析错误。
内容的提问来源于stack exchange,提问作者JayM
相关产品推荐
相关产品推荐

