首页 > 解决方案 > material-ui Date Picker 将空值保存为 Redux Form 中的 Date(0)

问题描述

我有一个 Redux 表单,它使用 material-ui 日期选择器来保存日期。如果有人没有选择日期并提交表单,则日期将保存为 1970-01-02。不幸的是,文档似乎没有包含任何处理它的道具,我无法通过验证来解决它——这些字段必须是可选的。

当没有给出值时,是否有任何选项可以强制组件不输入 Date(0)?或者我应该使用另一个 DatePicker 工具吗?我们正在使用material-ui v.0.19.4。我已经尝试过使用只会在更改时改变的空状态,但它没有帮助。

这就是Fields的样子。

      <Field
        name="endOfPartnership"
        type="text"
        component={DatePicker}
        className={css.fullWidth}
        floatingLabelFocusStyle={styles.floatingLabelColor}
        underlineFocusStyle={styles.floatingLabelColor}
        floatingLabelText={intl.formatMessage(defineMessages.endOfPartnership)}
        fullWidth
        formatDate={formatDate}
        minDate={minDate}
      />

标签: reactjsmaterial-uiredux-form

解决方案


我找到了行为的定义位置,仅供您参考。从他们的源代码。

https://github.com/mui-org/material-ui/blob/v0.x/src/DatePicker/DatePicker.js

有这条线。

value={this.state.date ? formatDate(this.state.date)

在哪里formatDate

  formatDate = (date) => {
    if (this.props.locale) {
      const DateTimeFormat = this.props.DateTimeFormat || dateTimeFormat;
      return new DateTimeFormat(this.props.locale, {
        day: 'numeric',
        month: 'numeric',
        year: 'numeric',
      }).format(date);
    } else {
      return formatIso(date);
    }
  };

我想这就是为什么日期总是“格式正确”的原因。


推荐阅读