[英]how to put keys in a for loop in react
I have a key problem in my condition in react with a for loop, it gives me a warning我在使用 for 循环时遇到一个关键问题,它给了我一个警告
I inserted my keys correctly, however I think but i have: "Warning: Each child in a list should have a unique "key" prop."我正确地插入了我的钥匙,但我认为但我有:“警告:列表中的每个孩子都应该有一个独特的“钥匙”道具。” error
错误
//Création des boutons
const buttons = [];
for (const page of pageNumbers) {
//if page is first or endPage
if (page === 1 || page === totalPages) {
buttons.push(
<>
<li
key={"1"}
className={`page-item ${
currentPage == page ? "active" : ""
}`}
>
<Button
className="page-link btnPaginate btn btn-link"
variant="link"
value={page}
onClick={() => props.handlePaginate(page)}
>
{page}
</Button>
</li>
</>
);
}
//if page is not first or not endPage
else if (page >= currentPage - 1 && page <= currentPage + 1) {
buttons.push(
<>
<li
key={"2"}
className={`page-item ${
currentPage == page ? "active" : ""
}`}
>
<Button
className="page-link btnPaginate btn btn-link"
variant="link"
value={page}
onClick={() => props.handlePaginate(page)}
>
{page}
</Button>
</li>
</>
);
}
//show left dots
else if (showDotsLeft && page === 2) {
buttons.push(
<>
<li
key={"3"}
className={`page-item ${
currentPage == page ? "active" : ""
}`}
>
<Button
className="page-link btnDotsLeft btn btn-link"
variant="link"
key="dots-left"
>
...
</Button>
</li>
</>
);
}
//show right dots
else if (showDotsRight && page === currentPage + 2) {
buttons.push(
<>
<li
key={"4"}
className={`page-item ${
currentPage == page ? "active" : ""
}`}
>
<Button
className="page-link btnDotsRight btn btn-link"
variant="link"
>
...
</Button>
</li>
</>
);
}
}
I inserted my keys correctly, however I think but i have: "Warning: Each child in a list should have a unique "key" prop."我正确地插入了我的钥匙,但我认为但我有:“警告:列表中的每个孩子都应该有一个独特的“钥匙”道具。” error
错误
You should add a key to each child as well as each element inside children .您应该为每个孩子以及 children 中的每个元素添加一个键。
This way React can handle all the minimal DOM changes,这样 React 可以处理所有最小的 DOM 变化,
So you need to set key
prop for each <Button />
too!所以你也需要为每个
<Button />
设置key
属性!
The key
needs to be added into the top level element.需要将
key
添加到顶级元素中。
In your example you have a React.Fragment
as a top level element instead of the <li>
you added the key into.在您的示例中,您有一个
React.Fragment
作为顶级元素,而不是<li>
您将密钥添加到其中。
solution found... Use <React.Fragment key={page}> rather than <>找到解决方案...使用 <React.Fragment key={page}> 而不是 <>
<React.Fragment key={page}>
<li
key="1"
className={`page-item ${
currentPage == page ? "active" : ""
}`}
>
<Button
key="2"
className="page-link btnPaginate btn btn-link"
variant="link"
value={page}
onClick={() => props.handlePaginate(page)}
>
{page}
</Button>
</li>
</React.Fragment>
Thanks for your comments and aids感谢您的意见和帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.