【问题标题】:React stateless functional component should return null but receiving errorReact 无状态功能组件应该返回 null 但收到错误
【发布时间】:2018-04-12 00:17:19
【问题描述】:

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

这是组件:

从“反应”导入反应; 从 '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;

传入的props:

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.

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    渲染没有返回任何内容。

    您缺少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;
            }
        })
    }
    

    【讨论】:

    • 是的,就是这样
    猜你喜欢
    • 2016-02-15
    • 1970-01-01
    • 2023-03-30
    • 2017-03-16
    • 2016-04-17
    • 1970-01-01
    • 2020-12-27
    • 2017-01-21
    • 1970-01-01
    相关资源
    最近更新 更多