遇到两个拥有相同钥匙的孩子 (React)
Encountered two children with the same key (React)
当我们从方法返回的两个或多个元素具有相同的map()
propkey
时,会出现 React 错误“遇到两个具有相同键的孩子”。
要解决该错误,请为每个元素的 prop 提供唯一值key
或使用索引参数。
下面是错误如何发生的示例。
const 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
prop 的属性,但该name
属性在所有对象中都不是唯一的。
使用index
作为键
解决错误的一种方法是使用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方法的函数
被调用,其中包含数组中的每个元素以及正在处理的当前元素的索引。
index
是唯一的,但是,将它用于道具不是最佳做法,key
因为它不稳定并且可以在渲染之间更改。更好的解决方案是使用一个值来唯一标识数组中的每个元素。
使用唯一标识符作为键
在示例中,我们可以使用id
对象的属性,因为每个属性都id
保证是唯一的。
const 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;
Using the id
for the key
prop is much better because we are guaranteed that
the object with id
of 1
will always have a name
property equal to Alice
.
key
prop for performance reasons. The key
prop enables React to make sure it only updates the list elements that change between renders.When each element in an array has a unique key, it’s much easier for React to
determine which list elements changed.
You could use the index
for the key
prop, however, this could cause React to
do more work behind the scenes than it would with a stable value like a unique
id
.
话虽如此,除非您呈现包含数千个元素的数组,否则您很有可能不会注意到使用索引和唯一标识符之间的任何区别。
将 key 属性添加到 React Fragment时,请确保使用冗长的语法。
请注意,您不应尝试访问该key
属性,否则警告
Key 不是 prop。尝试访问它会导致undefined
被引发。