我有一个简单的组件来显示无效的表单条目,显然,仅当所述表单条目无效时才应显示一条消息。据我所知,我正确地使用了条件返回语句,但是仍然出现错误。

这是组件:

从'react'导入React;
    从'prop-types'导入PropTypes;

function FormErrors ({formErrors}) {
    Object.keys({formErrors}).map((field, i) => {
        if ({formErrors}[field].length > 0) {
            return (
                <p key={i}>{field} {formErrors[field]}</p>
            )
        } else {
            return null;
        }
    })
}

export default FormErrors;


传递的道具:

formErrors: {email: '', password: ''};


和我收到的错误消息:

Invariant Violation: FormErrors(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.

最佳答案

渲染未返回任何内容。


您缺少return

function FormErrors ({formErrors}) {
    return Object.keys({formErrors}).map((field, i) => {
    // ^^ add this return
        if ({formErrors}[field].length > 0) {
            return (
                <p key={i}>{field} {formErrors[field]}</p>
            )
        } else {
            return null;
        }
    })
}

09-19 22:25