表单不提交Material UI DateTimePicker的默认值

Posted

技术标签:

【中文标题】表单不提交Material UI DateTimePicker的默认值【英文标题】:Form does not submit default value of Material UI DateTimePicker 【发布时间】:2022-01-17 03:04:47 【问题描述】:

我使用 React 作为前端,使用 Ruby on Rails 作为后端。我正在尝试通过表单提交我的 materialUI DateTimePicker 的值,但它仅在我更改默认 DateTimePicker 的值时才有效,但在我仅使用当前 DateTime 的默认值提交表单时不起作用。 我在提交表单时尝试显示 formData,它表明该值确实存在但没有插入后端。

这是我在前端的 DateTimePicker

<LocalizationProvider dateAdapter=AdapterDateFns>
              <DateTimePicker
                renderInput=(params) => (
                  <TextField
                    id="deadline_input"
                    type="date"
                    name="task[deadline]"
                    value=deadline
                    className=classes.dateTimePicker
                    ...params
                  />
                )
                value=deadline
                onChange=(newDate: Date | null) => 
                  newDate && dispatch(setDeadline(newDate));
                
              />
</LocalizationProvider>

这是我在控制台记录表单数据时得到的结果,我可以在这里看到我的截止日期

(4) [Array(2), Array(2), Array(2), Array(2)]
0: (2) ['task[title]', 'dfad']
1: (2) ['task[description]', 'fdfdsf']
2: (2) ['task[deadline]', '12/14/2021 12:43 am']
3: (2) ['task[tag]', 'dfad']
length: 4
[[Prototype]]: Array(0)

这就是后端服务器上发生的事情

Processing by Api::V1::TasksController#create as */*
  Parameters: "task"=>"title"=>"dfad", "description"=>"fdfdsf", "deadline"=>"12/14/2021 12:43 am", "tag"=>"dfad"
  TRANSACTION (0.5ms)  BEGIN
  ↳ app/controllers/api/v1/tasks_controller.rb:20:in `create'
  Task Create (1.8ms)  INSERT INTO "tasks" ("title", "description", "tag", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["title", "dfad"], ["description", "fdfdsf"], ["tag", "dfad"], ["created_at", "2021-12-13 16:43:21.917824"], ["updated_at", "2021-12-13 16:43:21.917824"]]
  ↳ app/controllers/api/v1/tasks_controller.rb:20:in `create'
  TRANSACTION (17.4ms)  COMMIT
  ↳ app/controllers/api/v1/tasks_controller.rb:20:in `create'
Completed 201 Created in 37ms (Views: 1.3ms | ActiveRecord: 19.7ms | Allocations: 2182)

当我更改有效的 DatePicker 的值时,我还附加了输出

(4) [Array(2), Array(2), Array(2), Array(2)]
0: (2) ['task[title]', 'adfaf']
1: (2) ['task[description]', 'dsfdsf']
2: (2) ['task[deadline]', '12/01/2021 04:08 am']
3: (2) ['task[tag]', 'test']
length: 4
[[Prototype]]: Array(0)
Started POST "/api/v1/tasks" for ::1 at 2021-12-14 00:46:23 +0800
Processing by Api::V1::TasksController#create as */*
  Parameters: "task"=>"title"=>"adfaf", "description"=>"dsfdsf", "deadline"=>"12/01/2021 04:08 am", "tag"=>"test"
  TRANSACTION (0.3ms)  BEGIN
  ↳ app/controllers/api/v1/tasks_controller.rb:20:in `create'
  Task Create (0.8ms)  INSERT INTO "tasks" ("title", "description", "tag", "created_at", "updated_at", "deadline") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id"  [["title", "adfaf"], ["description", "dsfdsf"], ["tag", "test"], ["created_at", "2021-12-13 16:46:23.468751"], ["updated_at", "2021-12-13 16:46:23.468751"], ["deadline", "2021-01-12 04:08:00"]]
  ↳ app/controllers/api/v1/tasks_controller.rb:20:in `create'
  TRANSACTION (12.2ms)  COMMIT
  ↳ app/controllers/api/v1/tasks_controller.rb:20:in `create'
Completed 201 Created in 29ms (Views: 0.9ms | ActiveRecord: 13.3ms | Allocations: 2175)

以防万一您需要我的表单提交处理程序

 const handleSubmit = (e) => 
    e.preventDefault();
    formSubmit(e.target);
  ;

  const formSubmit = async (formData) => 
    let data = new FormData(formData);
    console.log(Array.from(data));
      await fetch(api_url + "/tasks", 
        method: "POST",
        mode: "cors",
        body: data,
      )
        .then((response) => response.json())
        .then((response) => 
          dispatch(setTasks(tasks.concat([response])));
          dispatch(resetTask());
        )
        .catch((error) => console.log(error));
  ;

【问题讨论】:

【参考方案1】:

我意识到发送到 api 的表单数据中的日期格式是“MM/dd/yyyy”而不是“yyyy/mm/dd”的错误格式,这导致日期被混淆带有月份,当日期大于 12 时返回 null(因为月份不能大于 12)。

我只需要将 dateTimePicker 的格式更改为“dd/MM/yyyy”,而不是默认的“MM/dd/yyyy”。 “yyyy/MM/dd”和“dd/MM/yyyy”都可以在发送数据到数据库时找到。

这就是我在 dateTimePicker 中更改格式的方式

<LocalizationProvider dateAdapter=AdapterDateFns>
              <DateTimePicker
                renderInput=(params) => (
                  <TextField
                    id="deadline_input"
                    type="text"
                    name="task[deadline]"
                    className=classes.dateTimePicker
                    ...params
                  />
                )
                value=deadline
                inputFormat="dd/MM/yyyy hh:mm a"
                onChange=(newDate: Date | null) => 
                  newDate && dispatch(setDeadline(newDate));
                
              />
</LocalizationProvider>

只需将其添加到 dateTimePicker

inputFormat="dd/MM/yyyy"

只是发布答案,以便以后遇到同样问题的人可能会有所帮助

【讨论】:

以上是关于表单不提交Material UI DateTimePicker的默认值的主要内容,如果未能解决你的问题,请参考以下文章

React Hook 表单 + Material UI 复选框

需要在不使用 onChange 回调的情况下获取下拉菜单的值 - (material-ui reactjs)

验证失败时阻止表单提交(Angular Material)

带有 Formik 的 Material UI 单选按钮 - 未设置 onSubmit 的值

Material-ui Autocomplete 警告 提供给 Autocomplete 的值无效

Material UI IconButton onClick 不允许处理事件