注释从这开始~
总览
当咱们从map()
办法返回的两个或两个以上的元素具备雷同的key
属性时,会产生"Encountered two children with the same key"谬误。为了解决该谬误,为每个元素的key
属性提供举世无双的值,或者应用索引参数。
这里有个例子来展现谬误是如何产生的。
// App.jsconst App = () => { // ️ name property is not a unique identifier const people = [ {id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, {id: 3, name: 'Alice'}, ]; /** * ⛔️ Encountered two children with the same key, `Alice`. * Keys should be unique so that components maintain their identity across updates. * Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version. */ return ( <div> {people.map(person => { return ( <div key={person.name}> <h2>{person.id}</h2> <h2>{person.name}</h2> </div> ); })} </div> );};export default App;
上述代码片段的问题在于,咱们在每个对象上应用name
属性作为key
属性,然而name
属性在整个对象中不是举世无双的。
index
解决该问题的一种形式是应用索引。它是传递给map
办法的第二个参数。
const App = () => { const people = [ {id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, {id: 3, name: 'Alice'}, ]; // ️ now using index for key return ( <div> {people.map((person, index) => { return ( <div key={index}> <h2>{person.id}</h2> <h2>{person.name}</h2> </div> ); })} </div> );};export default App;
咱们传递给Array.map
办法的函数被调用,其中蕴含了数组中的每个元素和正在解决的以后元素的索引。
索引保障是惟一的,然而用它来做key
属性并不是一个最好的做法。因为它不稳固,在渲染期间会发生变化。
惟一标识
更好的解决方案是,应用一个能惟一标识数组中每个元素的值。
在下面的例子中,咱们能够应用对象上的id
属性,因为每个id
属性保障是惟一的。
// App.jsconst App = () => { const people = [ {id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, {id: 3, name: 'Alice'}, ]; // ✅ now using the id for the key prop return ( <div> {people.map(person => { return ( <div key={person.id}> <h2>{person.id}</h2> <h2>{person.name}</h2> </div> ); })} </div> );};export default App;
应用id
作为key
属性好多了。因为咱们保障了对象id
属性为1
时,name
属性总是等于Alice
。
React应用咱们传递给key
属性的值是出于性能方面的思考,以确保它只更新在渲染期间变动的列表元素。
当数组中每个元素都领有举世无双的key
时,React会更容易确定哪些列表元素产生了变动。
你能够应用index
作为key
属性。然而,这可能会导致React在幕后做更多的工作,而不是像举世无双的id
属性那样稳固。
尽管如此,除非你在渲染有成千上万个元素的数组,否则你很有可能不会留神到应用索引和惟一标识符之间有什么区别。