【问题标题】:How to specify keys in React Bootstrap table如何在 React Bootstrap 表中指定键
【发布时间】:2026-01-18 18:40:01
【问题描述】:

使用 React Bootstrap 表时,我收到警告 Warning: Each child in a list should have a unique "key" prop. 我已经阅读了有关列表的必要性,但不确定应该在哪里为表设置键?我的桌子看起来像这样

 <Table size="sm" responsive="sm" bordered hover striped>
                <thead>
                <tr>
                    <th>Col1</th>
                    <th>Col2</th>
                    <th>Col3</th>
                    <th>Col4</th>
                </tr>
                </thead>
                <tbody>
                { histories.map((h) => (
                    <tr>
                        <th>{ h.col1} </th>
                        <th> { h.col2}</th>
                        <th> { h.col3}</th>
                        <th>{ h.col4}</th>
                    </tr>
                )) }
                </tbody>
            </Table>

【问题讨论】:

  • 密钥可以是任何东西,如果消除警告很重要,甚至可以是硬编码的 (&lt;th key="1"&gt;Col1&lt;/th&gt;)。如果您有要迭代的数据,则可以是 id、名称或其他任何内容。或者如果你真的想全力以赴,你可以为每个项目生成一个 uuid。
  • 如果histories 有一个id,你可以做&lt;tr key={h.id}&gt;,这很可能是警告的来源

标签: reactjs react-bootstrap react-bootstrap-table


【解决方案1】:

如果有histories 的 ID,这将起作用。

{ histories.map((h) => (
  <tr key={h.id}>
    <th>{ h.col1} </th>
    <th> { h.col2}</th>
    <th> { h.col3}</th>
    <th>{ h.col4}</th>
  </tr>
)) }

密钥可以是任何东西(如果你愿意,甚至可以是h.col1),只要它在该列表中是唯一的。拥有它并不是非常重要(因此是警告而不是错误),但是当您迭代某些数据并从中呈现列表时,这绝对是一个好习惯,以防止一些不可预测的行为,并帮助 React 完成它正确的事情。

【讨论】:

  • 谢谢。我不知道的部分是它需要成为 的一部分