React - proptypes 验证 - return 错误不起作用但抛出

React - proptypes validation - return Error doesnt work but throw does

所以,我正在查看 react proptypes 选项,我想检查子项是否是特定类型,这非常简单,正如此处所述:https://facebook.github.io/react/docs/reusable-components.html#prop-validation 我应该 return错误对象并没有抛出。 但是当我 return 一个 Error 对象时它不会打印到控制台,但是如果我抛出一个 Error 对象一切正常。

propTypes 对象:

const propTypes = {
        children: function(props, propName) {
            const children = props[propName];
            React.Children.forEach(children, (child) => {
                if (child.type !== Field) {
                    // doesnt work
                    return new Error('Error');
                }
                return;
            });
        }
    };

const propTypes = {
        children: function(props, propName) {
            const children = props[propName];
            React.Children.forEach(children, (child) => {
                if (child.type !== Field) {
                    // does work
                    throw new Error('Error');
                }
                return;
            });
        }
    };

我该怎么办?

forEach 循环返回不会生成封闭函数 return。您最好做的是使用简单的 for 循环或 Array.prototype.some

const propTypes = {
  children: function(props, propName) {
    const children = props[propName];
    const invalid = React.Children.some(children, child => child.type !== Field);
    if (invalid) {
      return new Error('Error');
    }
  }
};