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

React warns about passed prop with value null, where the PropType for the prop is not required

本文关键字:prop PropType 其中 警告 null React      更新时间:2023-09-26

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

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

我该如何改变React以允许null | string |对象与此形状?谢谢你!

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

完整代码是:

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;

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

更新:我采用了这样的解决方案:

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.`
      );
    }
  },
};

阅读本期和本期,了解过去发生的讨论。只需使props.error可选并检查代码中的值。否则,您将需要实现自己的自定义道具验证。

From the docs:

// 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.'
    );
  }
}