我有一个 React 组件需要将 this.props.children
分解成 block ,并在包装元素(即子组件网格)中呈现每个 block 。
我正在关注 airbnb 的 React linting,其中包含一条规则 prevents me using the array index as a key :
react/no-array-index-key : Do not use Array index in keys
此规则指定我需要为每组子项设置一个唯一键,而不是数组索引 - 但我没有其他可用的标识符。
在这种情况下可以忽略此规则吗?
最佳答案
数组索引会产生错误的键,因为索引本身并不唯一标识特定的数组元素,而是数组中特定位置的任何元素。如果这种情况发生变化,识别就会中断。
构成每个 block 的项目是否有一个 ID?然后你可以生成一个 key ,例如通过散列 ID 的组合来唯一标识每个 block 。
如果这不是一个选项,请使用数组索引并忽略该消息。但是,您应该尽量避免这种情况:
When you don't have stable IDs for rendered items, you may use the item index as a key as a last resort:
const todoItems = todos.map((todo, index) => // Only do this if items have no stable IDs <li key={index}> {todo.text} </li> );
We don't recommend using indexes for keys if the items can reorder, as that would be slow.
关于javascript - 将 child 分成 block 和 "react/no-array-index-key",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42983067/