【问题标题】:What type of error should this be?这应该是什么类型的错误?
【发布时间】:2017-04-25 01:14:20
【问题描述】:

以这段代码为例:

class Wizard extends Component {
    constructor(props) {
        super(props);

        this.state = {
            steps: this.props.children ? this.props.children.length : null
        }
    }

    componentWillMount() {
        if (this.state.steps === null) {
            throw new Error(
                "The <Wizard /> component requires <Step /> components as children"
            );
        }
    }
}

这应该是什么类型的错误?我觉得应该有一个RequirementError,但我从来没有听说过。

【问题讨论】:

    标签: javascript reactjs error-handling


    【解决方案1】:

    所以我认为这是一个 PropType 错误,由 React 的 PropTypes 模块处理。这是文档页面的链接:

    Typechecking with PropTypes

    PropTypes 将对组件的 props(恰当命名)运行类型检查,并根据它们是否缺少必需的键来抛出信息/错误消息。

    代码示例:

    import PropTypes from 'prop-types';
    
    class MyComponent extends React.Component {
      render() {
        // This must be an array of children or it will warn.
        const children = this.props.children;
        return (
          <div>
            {children}
          </div>
        );
      }
    }
    
    MyComponent.propTypes = {
      children: PropTypes.arrayOf(PropTypes.element).isRequired
    };
    

    编辑:脱离 React 的上下文,我认为错误类型是 ChildType 错误

    【讨论】:

    • 我引用了你对我问题的编辑。不过,我真的对与库/框架无关的答案很感兴趣。
    • Framework 不可知论我认为这是一个 ChildType 错误,这只是感觉最合适的,因为 Children 只是一个 Child 对象的数组,而 ChildrenType 的长度是 3 个字符:(。我编辑了我的答案以反映这一点。
    • 好的,这将是一个自定义错误类型。我不是想成为一个痛苦的人,但我正在寻找更高层次的答案。我认为我在示例中过于具体,这是我的错。
    • 其实我会接受你的回答,因为我没有正确地问我的问题,而你提供了一个很好的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    • 2016-10-18
    • 1970-01-01
    • 2021-05-10
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多