React组件中第二个.map函数报唯一key prop错误的排查
问题分析与解决
你遇到的问题根源在于key属性放错了位置:React要求列表渲染时,.map()返回的最外层元素必须携带唯一的key prop,而你把第二个.map()的key加在了<tr>内部的<th>上,导致React依然识别不到<tr>的唯一标识,警告自然不会消失。
修复后的代码
import React from 'react' import { Table } from 'react-bootstrap' const ActivityTable = () => { const activities = [{ id: 100, name: 'reading' }, { id: 101, name: 'coding' }, { id: 200, name: 'eating' },] const date = new Date(); const currentDay = date.getDate(); const currentMonth = date.getMonth() + 1; const currentYear = date.getFullYear(); const getAllDaysInMonth = (month, year) => Array.from( { length: new Date(year, month, 0).getDate() }, // get next month, zeroth's (previous) day (_, i) => new Date(year, month - 1, i + 1) // get current month (0 based index) ); const allDatesInMonth = getAllDaysInMonth(currentMonth, currentYear) const listOfCurrentDays = allDatesInMonth.map(x => x.toLocaleDateString([], { day: "numeric" })) //console.log(allDatesInMonth.map(x => x.toLocaleDateString([], { month: "short", day: "numeric" }))) if (currentDay >= 0 || currentDay < 8) { var listOfCurrentWeekDays = listOfCurrentDays.slice(0, 7) } else if (currentDay > 7 || currentDay < 15) { var listOfCurrentWeekDays = listOfCurrentDays.slice(7, 14) } else if (currentDay > 14 || currentDay < 22) { var listOfCurrentWeekDays = listOfCurrentDays.slice(14, 21) } else if (currentDay > 21) { var listOfCurrentWeekDays = listOfCurrentDays.slice(20, 31) } console.log(listOfCurrentWeekDays) return ( <Table striped> <thead> <tr> <th>#</th> { (listOfCurrentWeekDays).map(function (item, key) { return ( <th key={key}> {item} </th> ) }) } </tr> </thead> <tbody> { (activities).map(function (item, key) { // 把key从<th>移到<tr>上 return ( <tr key={item.id}> <th> {item.name} </th> </tr> ) }) } </tbody> </Table> ) } export default ActivityTable
关键说明
- 第一个
.map()是正确的:返回的<th>是列表的直接子元素,key加在这个标签上符合要求 - 第二个
.map()的直接输出是<tr>,所以必须把key绑定到<tr>上,内部的<th>不需要额外加key(除非<th>内部还有另一个列表渲染)
内容的提问来源于stack exchange,提问作者LyNox
相关产品推荐
相关产品推荐

