React中使用prop-types对TreeNode的depth属性多重验证出现重复键警告如何解决?
问题描述
我正在开发一个名为TreeNode的React组件,该组件接收名为depth的prop,要求depth的值不得小于1。我使用prop-types库添加了必要的prop验证以确保这一约束,简化后的代码如下:
const TreeNode = ({ depth }) => { ... } TreeNode.propTypes = { depth: (PropTypes.number.isRequired), depth: (props, propName, componentName) => { if (props[propName] < 1) { return new Error( `Invalid prop ${propName} supplied to ${componentName}. It must be greater than 0.` ); } } }
代码功能正常,但触发了ESLint警告:
[eslint] src\Components\TreeNode.js Line 42:5: Duplicate key 'depth' no-dupe-keys Search for the keywords to learn more about each warning. To ignore, add // eslint-disable-next-line to the line before. WARNING in [eslint] src\Components\TreeNode.js Line 42:5: Duplicate key 'depth' no-dupe-keys webpack compiled with 1 warning
请问如何在使用prop-types进行验证的前提下避免这个警告?
解决方案
这个警告的原因是TreeNode.propTypes对象里重复定义了depth键——JavaScript对象中重复的键会被后面的覆盖,同时触发ESLint的no-dupe-keys规则。
要解决这个问题,需要把必填数字类型校验和数值范围校验合并到同一个depth的校验规则中,具体写法如下:
const TreeNode = ({ depth }) => { ... } TreeNode.propTypes = { depth: (props, propName, componentName) => { // 先复用prop-types的内置校验,确保depth是必填的数字类型 const typeError = PropTypes.number.isRequired(props, propName, componentName); if (typeError) { return typeError; } // 再校验数值范围 if (props[propName] < 1) { return new Error( `Invalid prop ${propName} supplied to ${componentName}. It must be greater than 0.` ); } } }
说明
这段代码先通过PropTypes.number.isRequired完成基础的类型和必填校验,只有当这一步通过后,才会进行数值范围的校验。既满足了所有业务约束,又避免了重复键的问题,完全符合ESLint规则。
内容的提问来源于stack exchange,提问作者Harsh Narwariya
相关产品推荐
相关产品推荐

