使用 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>
uj5u.com熱心網友回復:
這會起作用,因為histories.
{ 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 完成它事情正確。
uj5u.com熱心網友回復:
您可以傳遞密鑰,例如:
{ histories.map((h, key) => (
<tr key={key}>
</tr>
)) }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/354898.html
上一篇:如何為typescript輸入一個React.createContext,它需要一個ref和一個setState函式?
