遍历时,存在多个根标签,如果使用<></>无法正确赋值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>
	)
}
11-19 11:51