My App

Key 注意事项

Key 注意事项

这里是上面视频中的两个沙盒,附有评论解释视频中略过的一些内容:

import StickerPad from './StickerPad';

function App() {
  return (
    <>
      <p>Click around to add stickers!</p>
      <StickerPad />
    </>
  );
}

export default App;

邀请宾客名单:

import React from 'react';

function App() {
  const [invitees, setInvitees] = React.useState([
    'J. Jonah Jameson',
    'Mary Jane',
    'Aunt May',
  ]);

  // NOTE: This form is incomplete. It should have:
  // • A <label> for each input
  // • A <form> tag, with submission behaviour
  //
  // I'm omitting them here because they're not
  // relevant to the problem at hand. Please don't
  // use this markup as a template for anything real 😅

  return (
    <>
      <h1>Invitees</h1>
      <ul>
        {invitees.map((item, index) => (
          <li key={index}>
            <input
              // the `defaultValue` attribute
              // allows us to initialize the input
              // to a particular value, without
              // binding the input to it. This
              // will produce an *uncontrolled*
              // input.
              defaultValue={invitees[index]}
            />
            <button
              onClick={() => {
                const nextInvitees = [...invitees];
                nextInvitees.splice(index, 1);
                
                setInvitees(nextInvitees);
              }}
            >
              Delete
            </button>
          </li>
        ))}
      </ul>
    </>
  );
}

export default App;

弯曲规则

在本课中,我们看到了一些使用数组索引作为 key 可能导致问题的例子。我在视频的最后提到,您可以通过遵循我在上一课中分享的“生成随机值”策略来避免所有这些问题。

但是,我们总是需要这么做吗?还是有时可以将数组索引作为键?

从技术上讲,如果顺序保持 100%一致,使用数组索引作为键是安全的。如果项目从未更改位置,就不会出现任何问题。

但是问题是:并不总是明显顺序何时会改变。有许多情况可能导致问题。以下是一个不完整的列表:

  • 删除项目。
  • 在数组的开始/中间添加新项。
  • 改变物品排序的方式(例如,升序→降序)。
  • 过滤项目以显示/隐藏某些元素。

有时候我认为使用数组索引作为键是安全的,但结果证明我错了。😬

最终,我达到了一个非常熟悉这些东西的阶段,如今我偶尔会将数组索引作为键,当我 100%确信这不会引起任何问题时(而且我有点懒 😅)。

但是在你达到那种舒适程度之前,我建议你总是花几分钟时间以正确的方式做事情,为数组中的每个元素生成真正独特的价值。虽然这一开始会多花一些时间,但可以避免未来很多的困惑。