【问题标题】:React warns about passed prop with value null, where the PropType for the prop is not requiredReact 警告传递的值为 null 的道具,其中道具的 PropType 不是必需的
【发布时间】:2016-08-29 17:14:00
【问题描述】:

我有一个组件接收 error 作为字符串或具有 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,
  ]),
};

完整代码为:

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

【问题讨论】:

  • 你能分享你的代码,以便我们检查吗?
  • @Md.EstiakAhmmed 添加了完整代码。

标签: javascript reactjs


【解决方案1】:

阅读this issuethis issue 了解过去发生的讨论。只需将props.error 设为可选并检查代码中的值。否则,您需要实现自己的自定义prop validation

来自文档:

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

【讨论】:

    猜你喜欢
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    • 2020-12-24
    • 1970-01-01
    • 2022-07-20
    • 2019-04-23
    • 2018-03-12
    相关资源
    最近更新 更多