我正在尝试定义一个
PropTypes.exact
(这同样适用于 PropTypes.shape
),其中一个道具必须是相同 exact
的数组。
这就是我现在所拥有的,在一个导出多个组件中使用的多个形状/精确值的文件中:
export const StatusLogLineShape = PropTypes.exact({
dt: PropTypes.number.isRequired,
indentLevel: PropTypes.number.isRequired,
stat: PropTypes.number.isRequired,
exp: PropTypes.boolean,
msg: PropTypes.string.isRequired,
children: PropTypes.arrayOf(StatusLogLineShape),
});
代码构建时没有与上述相关的错误或警告,但在浏览器中加载应用程序会产生以下控制台错误,对于带有
children
属性的行:
Uncaught ReferenceError: can't access lexical declaration 'StatusLogLineShape' before initialization
我明白为什么它会抛出错误,但是有什么办法可以让它工作吗?
在谷歌结果中进行更多挖掘后,我找到了一个可行的解决方案,如下:
const statLogLineShape = {
dt: PropTypes.number.isRequired,
indentLevel: PropTypes.number.isRequired,
stat: PropTypes.number.isRequired,
exp: PropTypes.bool,
msg: PropTypes.string.isRequired,
};
statLogLineShape.children = PropTypes.arrayOf(PropTypes.exact(statLogLineShape));
export const StatusLogLineShape = PropTypes.exact(statLogLineShape);
此解决方案来自https://medium.com/@spencerwhitehead7/defining-recursive-proptypes-6f5586d0bd35