反应:我应该将密钥添加到DOM还是足以将其保持在对象状态



出于性能原因,应避免使用 Warning: Each child in an array or iterator should have a unique "key" prop键。

目前尚不清楚是否应将key属性添加到DOM中。例如,我应该将key添加到React.createElement('li', {className: 'book'},中:

var books = [
    {key: 1, author: "aaa", title: "111"},
];
var BookView = createReactClass({
    render: function() {
        return React.createElement('li', {className: 'book'},
            this.props.author,
            " - ",
            React.createElement('i', null, this.props.title))
    },
});
var BooksView = createReactClass({
    render: function () {
        return React.createElement('ul', {className: 'books'},
            this.props.data.map(function(__) { return React.createElement(BookView, __); }))
    }
});
var booksArea = document.getElementById('booksArea');
ReactDOM.render(React.createElement(BooksView, {data: books}), booksArea);

在React文档中下降:

一个好的经验法则是地图((调用中的元素需要键。

因此,在您使用.map()

创建元素列表时,它的BooksView

由于您已经将key属性作为props传递给模型,这足以满足警告。

您需要将key Prop传递给重复元素。在这种情况下,BookView

由于您的模型已经具有关键属性,并且您将该模型作为道具对象,这应该足够。

最新更新