首页 > 解决方案 > 在反应中为数字类型初始化一个空值

问题描述

我正在开发一个锻炼记录器,用于记录用户执行的锻炼集。它要求用户从 a 中选择一个练习select,以及他们为该组所做的重​​量和次数。权重和集合将存储为 type number。我在前端使用 React,在后端使用 GraphQL。

我能否将这些值初始化为“空”数字,其中输入字段留空,但仍识别出这些字段的类型应为number. 目前,我将它们设置为未定义并且一切正常,但在控制台中我收到此警告消息onSubmit,这是我的问题源于:

Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component.
const initialState = {
  exerciseName: "",
  weight: undefined,
  reps: undefined,
  notes: "",
};

我可以将初始值设置为 0 并且它可以工作,但我不想让用户在忘记更改这些初始值时提交表单。对此的任何见解将不胜感激。

PS我也尝试将它们保留为空字符串,但是这会在提交表单时使反应应用程序崩溃并出现错误,因为后端期望值是 ofFloatInt类型。

标签: reactjsgraphqlgraphql-js

解决方案


推荐阅读