[英]Missing "key" prop for element in iterator and Prop spreading is forbidden
我的代码中出现了这 2 个错误,如何在不使用“suppress eslint-disable-next-line react/jsx-props-no-spreading/ or eslint-disable-next-line react/jsx-key”的情况下修复这些错误这条线?
<UitkTableHead>
{headerGroups.map((headerGroup) => (
<UitkTableRow {...headerGroup.getHeaderGroupProps()}> // Prop spreading is forbidden
{headerGroup.headers.map((column) => (
<UitkTableCell scope="col" {...column.getHeaderProps()}> //Missing "key" prop for element in iterator
{column.render('Header')}
</UitkTableCell>
))}
</UitkTableRow>
))}
我希望让代码停止显示这些错误,如何更改代码以使其发生而不是添加忽略注释。
编辑:这是我的规则
"rules": {
"@typescript-eslint/ban-ts-comment": [
"error",
{
"ts-ignore": "allow-with-description"
}
],
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn",
"class-methods-use-this": "off",
"no-shadow": "off",
"import/no-extraneous-dependencies": "off",
"no-use-before-define": "off",
"@typescript-eslint/no-use-before-define": ["error", {"variables": false}],
"import/extensions": "off",
"react/prop-types": "off",
"react/require-default-props": "off",
"@typescript-eslint/explicit-function-return-type": "off",
"global-require": "off",
"import/no-dynamic-require": "off",
"camelcase": "off",
"react/jsx-props-no-spreading": "off",
"no-empty-function": "off",
"@typescript-eslint/no-empty-function": "off",
"@angular-eslint/no-empty-lifecycle-method": "off"
}
迭代器中缺少元素的“键”道具
此错误来自于在 React 中对数组使用.map()
方法。 当您使用.map()
时,React 需要一种方法来在比较 DOM 时轻松区分它正在映射的每个项目。 要解决这个问题,您需要做的就是为每个项目添加一个具有唯一标识符的key
,如果您没有唯一标识符,则可以向.map()
添加一个参数来获取它的项目的索引目前正在使用:
{headerGroup.headers.map((column, index) => (
<UitkTableCell key={index} scope="col" {...column.getHeaderProps()}>
{column.render('Header')}
</UitkTableCell>
))}
重要说明,这种使用索引的方式只能在您自己无法提供唯一密钥的情况下使用,无论是通过生成唯一密钥的库还是通过自己为每个 object 提供key
属性。
禁止传播道具
解决该问题的最简单方法是告诉 ESLint 在解析该错误时不要考虑该文件,但有不同的方法:
/* eslint-disable react/jsx-props-no-spreading *
react/jsx-props-no-spreading
return
要呈现的映射 arguments:{headerGroups.map((headerGroup) => (
const hgProps = headerGroup.getHeaderGroupProps();
return (
<UitkTableRow {hgProps}>
{headerGroup.headers.map((column, index) => (
<UitkTableCell key={index} scope="col" {...column.getHeaderProps()}>
{column.render('Header')}
</UitkTableCell>
))}
</UitkTableRow>
)
))}
如果它也发生在uitkTableCell
的道具下方,您可以遵循相同的规则。 希望这可以帮助!
Prop spreading is forbidden 错误参考:
如何解决自定义路由组件中的 eslint 错误:“prop spreading is forbidden”?
对于缺少键错误:您需要提及 UitkTableCell 中 map 返回项的唯一值作为 <UitkTableCell scope="col" key={column.unique_id}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.