2017-04-25 108 views
1

拿这个存根作为一个例子:这是什么类型的错误?

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,但我从来没有听说过。

回答

1

所以我相信这是一个PropType错误,由React的PropTypes模块处理。这里有一个链接到文档页面:

Typechecking with PropTypes

PropTypes将在您的组件的道具(适当命名的)运行类型检查,并抛出基于如果缺少所需的密钥信息/错误消息。

代码示例:

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 
}; 

编辑:走出阵营的背景下,我认为错误的类型将是一个ChildType错误

+0

我引你编辑我的问题。尽管如此,我对库/框架不可知的答案真的很感兴趣。 –

+0

框架agnostically我会认为它是一个ChildType错误,只是觉得最合适的,因为孩子只是一个儿童对象的数组和ChildrenType是3个字符长:(我编辑我的答案,以反映这 –

+0

好吧,这将是一个自定义错误类型,我并不想成为一个痛苦,但我正在寻找更高层次的答案,我认为我在我的例子中过于具体,那是我的错, –