我是 React 和前端开发的初学者。 这是显示表格的“简单”代码。
function TableHeader() {
return (
<thead>
<tr>
<th>Name</th>
<th>Job</th>
</tr>
</thead>
);
}
function TableDataRow(row, index) {
return (
<tr key={index}>
<td>{row.name}</td>
<td>{row.job}</td>
</tr>
)
}
function TableBody(props) {
const characterData = props.characterData;
return (
<tbody>
{characterData.map((row, index) => <TableDataRow row={row} index={index}/>)}
</tbody>
);
}
class Table extends Component {
render() {
const { characterData } = this.props;
return (
<table>
<TableHeader />
<TableBody characterData={characterData} />
</table>
);
}
}
class App extends Component {
render() {
const characters = [
{
'name': 'Charlie',
'job': 'Janitor'
},
{
'name': 'Mac',
'job': 'Bouncer'
},
{
'name': 'Dee',
'job': 'Aspring actress'
},
{
'name': 'Dennis',
'job': 'Bartender'
}
];
return (
<div className="container">
<Table characterData={characters} />
</div>
);
}
}
错误如下:
Warning: Each child in a list should have a unique "key" prop.
Check the render method of
TableBody
. See https://banned-fb.example.com/react-warning-keys for more information. in TableDataRow (at Table.js:30) in TableBody (at Table.js:44) in table (at Table.js:42) in Table (at App.js:28) in div (at App.js:27) in App (at src/index.js:6)
表中的数据行为空。我认为对 TableDataRow 的调用存在问题。我可能做错了什么?
屏幕截图:
最佳答案
关键的事情只是一个警告,但你也应该修复它,原因是没有渲染,因为你的组件是这样的:
function TableDataRow(row, index) {...} // WRONG
函数组件只获取一个参数,即 props,您需要做的是:
function TableDataRow(props) {
const {row, index} = props; // get row and index out of props inside function
...
}
或
function TableDataRow({ row, index }) {...} // destructure the props in parameter
现在关于修复key警告:
而不是提供
key
到<tr>
里面TableDataRow
您需要提供TableDataRow
的 key ,像这样:
function TableDataRow({ row }) { // you have a little error here too, row should be inside curly braces or use props and get row from props inside the function
return (
<tr> // no need of key
<td>{row.name}</td>
<td>{row.job}</td>
</tr>
)
}
function TableBody(props) {
const characterData = props.characterData;
return (
<tbody>
{characterData.map((row, index) => <TableDataRow row={row} key={index}/>)} // key should be here
</tbody>
);
}
此外,您还应该使用索引作为键作为最后的手段(请参阅 docs 了解原因)。如果您的数据来自api
每个项目可能有一个 id
您可以使用它作为键,或者每个字符可能还有其他唯一的东西,如果没有,可以使用索引。
关于reactjs - React 不显示表格行中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54627322/