[英]React – Add unique key to array map
我想為該函數提供的返回元素添加一個唯一鍵。
function RowList() {
const rows = [<Row0 />, <Row1 />, <Row2 />, <Row3 />];
return (
<>
{rows.map(row => (
<tr key={?}>{row}</tr>
))}
</>
);
}
我試過了:
function Rows() {
const rows = [<Row0 />, <Row1 />, <Row2 />, <Row3 />];
return (
<>
{rows.map(row => (
<tr key={row}>{row}</tr>
))}
</>
);
}
但是[object Object]
作為鍵返回。
我也將無法做類似的事情
let x = 0
function Rows() {
const rows = [<Row0 />, <Row1 />, <Row2 />, <Row3 />];
return (
<>
{rows.map(row => (
<tr key={x = x + 1}>{row}</tr>
))}
</>
);
}
因為我稍后需要能夠刪除並添加回數組。
如您所知,您不能只這樣做:
// DON'T DO THIS
{rows.map((row, index) => (
<tr key={index}>{row}</tr>
))}
正如文檔所說,這是“最后的手段”,實際上只對靜態列表有用。 你說過你的列表不會是靜態的。
擁有像這樣的已經創建的元素數組而不是元素的數據數組是相當不尋常的。 如果你可以避免它,我會,並為數據條目提供可以用作鍵的持久 ID 值,例如( name
顯然是實際數據的替代品):
class RowInfo {
static id = 0;
constructor(name) {
this.name = name;
this.id = RowInfo.id++;
}
}
function RowList() {
const rows = [new RowInfo("one"), new RowInfo("two"), new RowInfo("three"), new RowInfo("four")];
return (
<>
{rows.map(({id, name}) => (
<tr key={id}><Row name={name}/></tr>
))}
</>
);
}
這假設它們都應該是相同類型的組件,當然,這可能不是真的。
如果您不能這樣做並且必須預先創建實際元素,我可能會創建包裝對象:
class RowInfo {
static id = 0;
constructor(element) {
this.element = element;
this.id = RowInfo.id++;
}
}
function RowList() {
const rows = [new RowInfo(<Row0 />), new RowInfo(<Row1 />), new RowInfo(<Row2 />), new RowInfo(<Row3 />)];
return (
<>
{rows.map(({id, element}) => (
<tr key={id}>{element}</tr>
))}
</>
);
}
或者,如果它們沒有您需要指定的任何道具,您可以讓 React 跟蹤它們,因為這是其工作的一部分:
class RowInfo {
static id = 0;
constructor(Comp) {
this.Comp = Comp;
this.id = RowInfo.id++;
}
}
function RowList() {
const rows = [new RowInfo(Row0), new RowInfo(Row1), new RowInfo(Row2), new RowInfo(Row3)];
return (
<>
{rows.map(({id, Comp}) => (
<tr key={id}><Comp/></tr>
))}
</>
);
}
這是一個活生生的例子:
const Row0 = () => <div>Row 0</div>; const Row1 = () => <div>Row 1</div>; const Row2 = () => <div>Row 2</div>; const Row3 = () => <div>Row 3</div>; const {Fragment} = React; class RowInfo { static id = 0; constructor(Comp) { this.Comp = Comp; this.id = RowInfo.id++; } } // Have to use <Fragment></Fragment> in the below instead of <></> because // Stack Snippet's version of Babel is out of date and // doesn't understand <></>. function RowList() { const rows = [new RowInfo(Row0), new RowInfo(Row1), new RowInfo(Row2), new RowInfo(Row3)]; return ( <Fragment> {rows.map(({id, Comp}) => ( <tr key={id}><Comp/></tr> ))} </Fragment> ); } ReactDOM.render(<RowList/>, document.getElementById("root"));
<div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.