Having two .map functions in React component and the second one gives the error 'Each child in a list should have a unique "key" prop.'

huangapple go评论66阅读模式
英文:

Having two .map functions in React component and the second one gives the error 'Each child in a list should have a unique "key" prop.'

问题

I'm getting an error that each child in a list should have a unique "key" prop.

这个错误是因为列表中的每个子元素都需要一个唯一的 "key" 属性。

The error only appears on the second .map function.

这个错误只在第二个 .map 函数中出现。

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) {
            return (
              <tr key={item.id}>
                <th>
                  {item.name}
                </th>
              </tr>
            )
          })
        }
      </tbody>
    </Table>
  )
}
export default ActivityTable

At first, I was using key={key} for both .map functions.

起初,我在两个 .map 函数中都使用了 key={key}。

I thought as both key values start with 0,1,2... that that was the reason why I was getting this error.

我以为因为两个 key 值都从 0、1、2... 开始,所以导致了这个错误。

I have added the id property to the activities array so that both .map functions have different keys.

我已经将 id 属性添加到 activities 数组中,以便两个 .map 函数具有不同的键。

But I'm still getting this error.

但是我仍然遇到这个错误。

英文:

I'm getting an error that each child in a list should have a unique "key" prop.

The error only appears on the second .map function.

import React from &#39;react&#39;
import { Table } from &#39;react-bootstrap&#39;
const ActivityTable = () =&gt; {
const activities = [{ id: 100, name: &#39;reading&#39; }, { id: 101, name: &#39;coding&#39; }, { id: 200, name: &#39;eating&#39; },]
const date = new Date();
const currentDay = date.getDate();
const currentMonth = date.getMonth() + 1;
const currentYear = date.getFullYear();
const getAllDaysInMonth = (month, year) =&gt;
Array.from(
{ length: new Date(year, month, 0).getDate() }, // get next month, zeroth&#39;s (previous) day
(_, i) =&gt; new Date(year, month - 1, i + 1)    // get current month (0 based index)
);
const allDatesInMonth = getAllDaysInMonth(currentMonth, currentYear)
const listOfCurrentDays = allDatesInMonth.map(x =&gt; x.toLocaleDateString([], { day: &quot;numeric&quot; }))
//console.log(allDatesInMonth.map(x =&gt; x.toLocaleDateString([], { month: &quot;short&quot;, day: &quot;numeric&quot; })))
if (currentDay &gt;= 0 || currentDay &lt; 8) {
var listOfCurrentWeekDays = listOfCurrentDays.slice(0, 7)
} else if (currentDay &gt; 7 || currentDay &lt; 15) {
var listOfCurrentWeekDays = listOfCurrentDays.slice(7, 14)
} else if (currentDay &gt; 14 || currentDay &lt; 22) {
var listOfCurrentWeekDays = listOfCurrentDays.slice(14, 21)
} else if (currentDay &gt; 21) {
var listOfCurrentWeekDays = listOfCurrentDays.slice(20, 31)
}
console.log(listOfCurrentWeekDays)
return (
&lt;Table striped&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;#&lt;/th&gt;
{
(listOfCurrentWeekDays).map(function (item, key) {
return (
&lt;th key={key}&gt;
{item}
&lt;/th&gt;
)
})
}
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
{
(activities).map(function (item, key) {
return (
&lt;tr&gt;
&lt;th key={item.id}&gt;
{item.name}
&lt;/th&gt;
&lt;/tr&gt;
)
})
}
&lt;/tbody&gt;
&lt;/Table&gt;
)
}
export default ActivityTable

At first, I was using key={key} for both .map functions.

I thought as both key values start with 0,1,2... that that was the reason why I was getting this error.

I have added the id property to the activities array so that both .map functions have different keys.

But I'm still getting this error.

答案1

得分: 1

问题在于你在th中使用了key;然而,你应该将它添加到tr中,因为它是列表项中最高级别的标签。

英文:

The problem is that you are using key in the th; however, you are expected to add it to tr, since it is the highest tag in the list item.

答案2

得分: 1

在第二个.map示例中,您将键应用于嵌套组件,而不是根组件——与第一个示例一样,您将键应用于映射组件的根部分。应注意键仅在父组件内相关。将键应用于映射组件的根tr标签应该能解决问题。

英文:

In your second .map example, you're applying the key to a nested component, not the root -- as with the first example, you're applying the key to the root of the mapped component. It should be noted that the key is only relevant within the parent component. Applying the key to the root tr tag of the mapped component should do the trick.

答案3

得分: 1

你之所以出现此错误是因为您将key属性赋予了&lt;th&gt;标签,而不是&lt;tr&gt;标签。

> 您应该将key属性赋予父元素。

为了解决这个问题,请使用以下代码:

{
  (activities).map(function (item, key) {
    return (
      &lt;tr key={item.id}&gt;
        &lt;th&gt;
          {item.name}
        &lt;/th&gt;
      &lt;/tr&gt;
    )
  })
}
英文:

You are getting this error because you are giving the key property to the &lt;th&gt; tag instead of &lt;tr&gt; tag.

> You should give key property to the parent.

In order to solve this problem, use the code below:

{
(activities).map(function (item, key) {
return (
&lt;tr key={item.id}&gt;
&lt;th&gt;
{item.name}
&lt;/th&gt;
&lt;/tr&gt;
)
})
}

答案4

得分: 1

你把密钥放错地方了。

{
activities.map(function (item, key) {
return (
<tr key={item.id}>
<th>
{item.name}
</th>
</tr>
)
})
}

它应该放在父元素上。

顺便说一句:尽量避免使用var,使用let和const更好。

let listOfCurrentWeekDays

if (currentDay >= 0 || currentDay < 8) {
listOfCurrentWeekDays = listOfCurrentDays.slice(0, 7)
} else if (currentDay > 7 || currentDay < 15) {
listOfCurrentWeekDays = listOfCurrentDays.slice(7, 14)
} else if (currentDay > 14 || currentDay < 22) {
listOfCurrentWeekDays = listOfCurrentDays.slice(14, 21)
} else if (currentDay > 21) {
listOfCurrentWeekDays = listOfCurrentDays.slice(20, 31)
}

希望这对你有帮助。 Having two .map functions in React component and the second one gives the error 'Each child in a list should have a unique "key" prop.'

英文:

You just put the key in the wrong place.

        {
activities.map(function (item, key) {
return (
&lt;tr key={item.id}&gt;
&lt;th&gt;
{item.name}
&lt;/th&gt;
&lt;/tr&gt;
)
})
}

It needs to be on the parent element.

Side note: Try to avoid using var, stick with let and const.

let listOfCurrentWeekDays
if (currentDay &gt;= 0 || currentDay &lt; 8) {
listOfCurrentWeekDays = listOfCurrentDays.slice(0, 7)
} else if (currentDay &gt; 7 || currentDay &lt; 15) {
listOfCurrentWeekDays = listOfCurrentDays.slice(7, 14)
} else if (currentDay &gt; 14 || currentDay &lt; 22) {
listOfCurrentWeekDays = listOfCurrentDays.slice(14, 21)
} else if (currentDay &gt; 21) {
listOfCurrentWeekDays = listOfCurrentDays.slice(20, 31)
}

I hope it will help you. Having two .map functions in React component and the second one gives the error 'Each child in a list should have a unique "key" prop.'

huangapple
  • 本文由 发表于 2023年5月7日 03:31:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76190743.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定