首頁 >web前端 >js教程 >為什麼我的 React Array 子級需要唯一的按鍵?

為什麼我的 React Array 子級需要唯一的按鍵?

Patricia Arquette
Patricia Arquette原創
2024-12-27 12:31:09518瀏覽

Why Do My React Array Children Need Unique Keys?

了解React.js 中數組子項的唯一鍵

在React 中,為數組子項分配唯一鍵以優化性能非常重要並避免不必要的重新渲染。

問題:
在使用JSON資料來源。

調查:

``

{rows}

``
``
var TableRowItem = Reactact.createClass( 渲染:函數() {

var td = function() {
  return this.props.columns.map(function(c) {
    return <td key={this.props.data[c]}>{this.props.data[c]}</td>;
  }, this);
}.bind(this);

return (<tr >{ td(this.props.item) }</tr>);

}
});
``

解:
問題源自於缺少唯一鍵

在TableRowItem 元件中呈現的元素。

為了確保 rows 陣列中的每個子項目都有唯一的 key 屬性,您還必須在 TableRowItem 元件中的元素中新增鍵。

var TableRowItem = React.createClass({
  render: function() {

    var td = function() {
      return this.props.columns.map(function(c) {
        return <td key={this.props.key + '-' + c}>{this.props.data[c]}</td>;
      }, this);
    }.bind(this);

    return (<tr >{ td(this.props.item) }</tr>);
  }
});

透過在

新增唯一鍵元素,React 可以追蹤各個元素並執行高效的更新,防止不必要的整行重新渲染。

以上是為什麼我的 React Array 子級需要唯一的按鍵?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn