我有一个React组件,其状态为errors: {}对象。该对象实质上是user: {}对象的镜像,该对象从组件中的表单获取数据。

错误对象将存储尝试保存到数据存储中返回的所有错误消息。

例如
如果此人忘记输入字段username,则响应将包含“错误”对象。实际的错误消息将位于:errors.username.message

如果存在该消息,则将显示该错误消息的组件。我通过prop errorText传递了潜在的错误消息:

<Input value={ user.username } name="username" errorText={ errors.username }
    placeholder="username"
    displayName="Database Username" type="text" onChange={ updateFormField } />


无论errors.username实际上是否是对象中的键,此方法都有效。

但是,我在输入组件中遇到错误,因为找不到messageundefined

我以为可以使用in测试密钥,但是这是非常错误的。这是我的输入组件:

export const Input = (props) => (
    <div className="form-group">
        <label htmlFor={ props.name }>{ props.displayName }</label>
            <input type={ props.type } value={ props.value } placeholder={ props.placeholder }
                name={props.name} id={props.name} onChange={ props.onChange } className="form-control"/>

        { "errorText" in props ? "message" in props.errorText ? (
            <label className="label label-danger">{ props.errorText.message }</label>
        ) : "" : (
            ""
        )}
    </div>
);


有什么建议么?

最佳答案

您正在将errorText={ errors.username }属性传递给Input组件。即使errors.username解析为undefined,也会设置此道具。这意味着Input组件中的道具看起来像{ errorText: undefined }

现在"errorText" in props解析为true,因为实际上有这样的键,但是"message" in props.errorText会引发错误,因为props.errorTextundefined

您可以将其更改为:

props.errorText !== undefined
  && props.errorText.message !== undefined
  && <label className="label label-danger">{props.errorText.message}</label>

10-06 12:42
查看更多