注释从这开始~

总览

当咱们从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属性那样稳固。

尽管如此,除非你在渲染有成千上万个元素的数组,否则你很有可能不会留神到应用索引和惟一标识符之间有什么区别。