reactjs - Ant Design DatePicker 组件在以具有初始值的动态形式显示数据时出错
问题描述
我正在使用 antd 动态表单作为更新表单。我的日期在一个数组中,我想用 < DatePicker /> 和 <Form.List /> 显示它们。但我得到了
moment.js:105 Uncaught TypeError: date.clone is not a function
index.js:1 组件出现上述错误:
//object itself
const module = {
id:1,module_dates:[{date:"04/07/2021"},...]
}
我将所有日期转换为与此“new Date(module.module_dates[0].date)”相似的日期,以确保格式为“Tue Jul 06 2021 03:00:00 GMT+0300 (GMT+03:00)”,但是仍然收到错误。表单组件在下面;
<Form
name='update_module'
onFinish={SubmitForm}
initialValues={{
module_dates: module.module_dates,
}}
>
<Form.List name='module_dates'>
{(fields, { add, remove }) => (
<>
{fields.map(({ key, name, fieldKey, ...restField }) => (
<Space
key={key}
align='baseline'
>
<Form.Item
{...restField}
name={[name, 'date']}
fieldKey={[fieldKey, 'date']}
>
<DatePicker />
</Form.Item>
<MinusCircleOutlined onClick={() => remove(name)} />
</Space>
))}
<Form.Item>
<Button
type='dashed'
onClick={() => add()}
icon={<PlusOutlined />}
>
Add date
</Button>
</Form.Item>
</>
)}
</Form.List>
<Form.Item>
<Button type='primary' htmlType='submit'>
Submit
</Button>
</Form.Item>
</Form>
如有必要,我也可以创建一个沙箱。已经谢谢了。
解决方案
根据AntD Documentation, DatePicker 组件接受时刻对象作为它的值,但给出了字符串。
您应该将日期转换为 .moment(module.module_dates[0].date)
甚至更好moment(module.module_dates[0].date, 'DD/MM/YYYY')
。