【问题标题】:material-ui Date Picker saves empty value as Date(0) in Redux Formmaterial-ui Date Picker 将空值保存为 Redux Form 中的 Date(0)
【发布时间】:2018-12-11 13:28:10
【问题描述】:

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

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

这就是字段的外观。

      <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}
      />

【问题讨论】:

  • 我认为你应该在服务器端处理这个问题,因为你永远无法控制客户端提交的内容。
  • @christopher_pk 对于某些字段 Date(0) 可能是有效的输入 - 例如生日字段。我只想关闭这个让 DatePicker 自动将 null 分配给 Date(0) 的奇怪功能。
  • 你试过defaultDate 道具吗?
  • @christopher_pk 两种情况(未定义,空)都返回 Date(0)。我想我会切换到redux-form's datepicker,因为它明显支持无输入。

标签: reactjs material-ui redux-form


【解决方案1】:

我找到了定义行为的地方,仅供您参考。来自他们的源代码。

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);
    }
  };

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

【讨论】:

  • 因此我们可以得出结论,它不适用于表单。无论如何,感谢您的意见。
【解决方案2】:

函数将日期解析为字符串时出现问题。

有人在日期转换方面遇到问题,并提出了一个非常难看的解决方法。我们切换到moment.js,它让我们避免了之前的问题,我可以确认它现在在没有输入的情况下可以正常工作=> materialUI datepicker 可以正常工作。

谢谢克里斯托弗!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-27
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 2021-10-12
    相关资源
    最近更新 更多