React警告传递的prop值为null,其中prop的PropType不是必需的

Max*_*kin 8 javascript reactjs

我有一个组件接收错误作为字符串或具有2个必需属性的对象.但是也可以为此道具传递null.在我当前的设置中,当传递null时,React会发出警告:

警告:失败的道具类型:error提供的 无效道具ErrorDialog

我应该为React改变什么来允许null | 字符串| 这个形状的物体?谢谢!

ErrorDialog.propTypes = {
  onResetError: PropTypes.func.isRequired,
  error: PropTypes.oneOfType([
    PropTypes.shape({
      id: PropTypes.number.isRequired,
      defaultMessage: PropTypes.string.isRequired,
    }),
    PropTypes.string,
  ]),
};
Run Code Online (Sandbox Code Playgroud)

完整的代码是:

import React, { PropTypes } from 'react';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import { FormattedMessage } from 'react-intl';

const ErrorDialog = ({ error, onResetError }) => {
  function renderError() {
    if (!error) {
      return null;
    } else if (typeof error === 'string') {
      return error;
    } else if (typeof error === 'object') {
      return <FormattedMessage {...error} />;
    }
    return null;
  }

  return (
    <Dialog
      modal={false}
      open={Boolean(error)}
      actions={
        <FlatButton
          label="OK"
          primary
          onTouchTap={onResetError}
        />
      }
    >
      {renderError()}
    </Dialog>
  );
};

ErrorDialog.propTypes = {
  onResetError: PropTypes.func.isRequired,
  error: PropTypes.oneOfType([
    PropTypes.shape({
      id: PropTypes.number.isRequired,
      defaultMessage: PropTypes.string.isRequired,
    }),
    PropTypes.string,
  ]),
};

export default ErrorDialog;
Run Code Online (Sandbox Code Playgroud)

我想隐藏对话框,当没有错误时,显示原始字符串,如果错误是字符串类型,并且如果指定了消息描述符则呈现已翻译的消息.

更新:我选择了这样的解决方案:

ErrorDialog.propTypes = {
  onResetError: PropTypes.func.isRequired,
  // eslint-disable-next-line consistent-return
  error(props, propName, componentName) {
    const prop = props[propName];
    if (prop !== null &&
        typeof prop !== 'string' &&
        !(typeof prop === 'object' && prop.id && prop.defaultMessage)) {
      return new Error(
        `Invalid prop \`${propName}\` supplied to ${componentName}. Validation failed.`
      );
    }
  },
};
Run Code Online (Sandbox Code Playgroud)

小智 7

阅读此问题此问题,以便进行过去的讨论.只需props.error选择并检查代码中的值.否则,您需要实现自己的自定义道具验证.

来自文档:

// You can also specify a custom validator. It should return an Error
// object if the validation fails. Don't `console.warn` or throw, as this
// won't work inside `oneOfType`.
customProp: function(props, propName, componentName) {
  if (!/matchme/.test(props[propName])) {
    return new Error(
      'Invalid prop `' + propName + '` supplied to' +
      ' `' + componentName + '`. Validation failed.'
    );
  }
}
Run Code Online (Sandbox Code Playgroud)