[英]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.