【发布时间】: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