下面是我浏览器控制台的错误:
Warning: Each child in a list should have a unique "key" prop. See https://reactjs.org/link/warning-keys for more information.
ExpenseList@http://localhost:3000/main.cfec1fef7369377b9a13.hot-update.js:29:7
div
Card@http://localhost:3000/static/js/main.chunk.js:2973:19
div
Expenses@http://localhost:3000/static/js/main.chunk.js:1482:97
div
App@http://localhost:3000/static/js/main.chunk.js:296:89
我相信它是在向我介绍 ExpenseList 类。下面是类:
import React from "react";
import ExpenseItem from "./ExpenseItem";
import './ExpensesList.css';
const ExpenseList = props => {
if (props.expenses.length > 0) {
return props.expenses.map((expense) => (
<ul className="expenses-list">
<ExpenseItem
key={expense.id}
title={expense.title}
amount={expense.amount}
date={expense.date}
/>
</ul>
));
}
return <h2 className="expenses-list__fallback">Found No Expenses</h2>;
}
export default ExpenseList;
我似乎找不到问题出在哪里,因为我已经放了 key 。
最佳答案
const ExpenseList = props => {
if (props.expenses.length > 0) {
return <ul className="expenses-list">
{props.expenses.map((expense) => (
<ExpenseItem
key={expense.id}
title={expense.title}
amount={expense.amount}
date={expense.date}
/>
))}
</ul>
}
return <h2 className="expenses-list__fallback">Found No Expenses</h2>;
}
评论里很多人说把key放在ul
里,但我觉得你应该这样重新格式化。
关于javascript - 我该如何解决这个 'key' 警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69359072/