【问题标题】:ReactJS | Objects are not valid as react children反应JS |对象作为反应子项无效
【发布时间】:2019-03-18 14:24:29
【问题描述】:

我正在使用 React 和 Formik 来创建管理表单。 (Error Handling, submission etc)。我在处理来自服务器的错误时遇到了一些麻烦。

为了解决这个问题,我使用了 Formik 的内置 <ErrorMessage />。所以,我在表单的第一个元素中添加了它。如下图:

<form onSubmit={handleSubmit}>
          <div className="pb-2">
            <label className="font-weight-bold" htmlFor="username">
              Username <Asterisk />
            </label>
            <Field
              validate={this.debounceUsernameValidation}
              className={classNames('form-control', {
                'is-invalid': errors.username && touched.username
              })}
              placeholder="Username (Required)"
              autoComplete="false"
              name="username"
              type="text"
            />
            {errors.username && touched.username ? (
              <div className="text-danger">{errors.username}</div>
            ) : null}
          </div>
          <ErrorMessage name={errors.username} component="div" className="text-danger small" />
</form>

但我收到以下错误:

Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead.

我不确定我做错了什么。你能帮我解决这个问题,让我明白这个错误是什么。我的意思是来自服务器端或客户端的错误应该是一个对象。

当 React 说 If you need to be an object, use an array instead 时。我真的不明白。感谢您的宝贵时间。

错误对象。这是由 Yup 生成的,它与 Formik 结合使用:

{ "username": "Username is Required", "password": "Password is required", "confirmPassword": "Password Confirmation is Required", "group": "Group is required" }

【问题讨论】:

  • errors.username 包含什么?如果它是一个会导致此问题的对象。
  • 嗯,错误是一个带有字符串的对象,包含客户端错误。检查错误对象的更新描述。你可以看到用户名是一个字符串。它也是来自服务器的字符串。

标签: javascript reactjs forms error-handling formik


【解决方案1】:

您使用 &lt;ErrorMessage ... /&gt; 错误。 name 属性应该是一个字符串,其值与错误对象的键值相同。像这样的:

<ErrorMessage component="div" name="username" />
// --> {touched.username && error.username ? <div>{error. username}</div> : null}

如果我们遵循文档:

name

name: string 必填

Formik 状态下的字段名称。要访问嵌套对象或数组,名称 > 还可以接受类似 lodash 的点路径,例如 social.facebook 或 >friends[0].firstName

查看文档中的示例:

https://jaredpalmer.com/formik/docs/api/errormessage

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 2021-02-10
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 2018-05-28
    相关资源
    最近更新 更多