解决React遍历每次渲染多个根元素导致无法为元素赋值key的问题
遍历时,存在多个根标签,如果使用<></>无法正确赋值key,代码如下:
function App() {
const list = [
{ id:1, name:"小明" },
{ id:2, name:"小田" },
{ id:3, name:"小王" }
]
const listContent = list.map(item => (
<>
<li>{item.name}</li>
<li>-----------</li>
</>
))
return (
<ul>{listContent}</ul>
)
}
使用Fragment可以解决
import { Fragment } from "react"
function App() {
const list = [
{ id:1, name:"小明" },
{ id:2, name:"小田" },
{ id:3, name:"小王" }
]
const listContent = list.map(item => (
<Fragment key={item.id}>
<li>{item.name}</li>
<li>-----------</li>
</Fragment>
))
return (
<ul>{listContent}</ul>
)
}