react/no-array-index-key 性能
它的作用
如果元素使用数组索引作为 key,将会发出警告。
为什么这是个问题?
使用数组索引作为 key 是一个糟糕的做法,因为索引并不能唯一标识你的元素。当数组被排序或在数组开头添加元素时,即使对应索引的元素本身没有改变,其索引值也会发生变化。这会导致不必要的重新渲染。
示例
此规则的错误代码示例:
jsx
things.map((thing, index) => <Hello key={index} />);此规则的正确代码示例:
jsx
things.map((thing, index) => <Hello key={thing.id} />);如何使用
通过配置文件或 CLI 启用此规则,可以使用以下方式:
json
{
"plugins": ["react"],
"rules": {
"react/no-array-index-key": "error"
}
}bash
oxlint --deny react/no-array-index-key --react-plugin