React之旅-05 List Key

每个React的初学者,在调试程序时,都会遇到这样的警告:**Warning: Each child in a list should have a unique "key" prop.**如下面的代码:

TypeScript 复制代码
const list = ['Learn React', 'Learn GraphQL'];

const ListWithoutKey = () => (
  <div>
    <ul>
      {list.map((item) => (
        <li>{item}</li>
      ))}
    </ul>
  </div>
);

这个警告提示我们,需要为列表中的每个元素添加 key 属性。如下面的代码:

TypeScript 复制代码
const ListWithoutKey = () => (
  <div>
    <ul>
      {list.map((item, index) => (
        <li key={index}>{item}</li>
      ))}
    </ul>
  </div>
);

使用上面的代码调试时,之前的警告会消失,但其实在其背后,有一个隐式的 bug。当你对列表进行重新排序时,特别是当你添加了非受控的元素,问题就会发生。

如果你的代码如下:

TypeScript 复制代码
const initialList = ['Learn React', 'Learn GraphQL'];

const ListWithUnstableIndex = () => {
  const [list, setList] = React.useState(initialList);

  const handleClick = event => {
    setList(list.slice().reverse());
  };

  return (
    <div>
      <ul>
        {list.map((item, index) => (
          <li key={index}>
            <label>
              {item}
            </label>
          </li>
        ))}
      </ul>

      <button type="button" onClick={handleClick}>
        Reverse List
      </button>
    </div>
  );
};

运行你的代码,点击按钮对列表进行重新排序,看样子,一切正常。

可是当你添加了不受控的元素时,假如你的代码如下:

TypeScript 复制代码
const initialList = ['Learn React', 'Learn GraphQL'];

const ListWithUnstableIndex = () => {
  const [list, setList] = React.useState(initialList);

  const handleClick = event => {
    setList(list.slice().reverse());
  };

  return (
    <div>
      <ul>
        {list.map((item, index) => (
          <li key={index}>
            <label>
              <input type="checkbox" />
              {item}
            </label>
          </li>
        ))}
      </ul>

      <button type="button" onClick={handleClick}>
        Reverse List
      </button>
    </div>
  );
};

在上述的代码中,checkbox 是非受控元素,当你运行上述的代码时,运行的结果,可能和你相像的不太一致。

TypeScript 复制代码
// 列表最初的样子

[x] Learn React
[ ] Learn GraphQL

// 点击按钮,列表重新排序后的样子

[x] Learn GraphQL
[ ] Learn React

这种结果显然不是你想要的,那这背后终究发生了什么呢?

TypeScript 复制代码
// 列表当初的样子

[x] Learn React (index = 1)
[ ] Learn GraphQL (index = 2)

// 点击按钮,列表重新排序后的样子

[x] Learn GraphQL (index = 1)
[ ] Learn React (index = 2)

那如何解决这个问题呢,办法当然有,这次,我们使用了相当稳定的元素作为 key 属性。代码如下:

TypeScript 复制代码
const initialList = [
  { id: 'a', name: 'Learn React' },
  { id: 'b', name: 'Learn GraphQL' },
];

const ListWithStableIndex = () => {
  const [list, setList] = React.useState(initialList);

  const handleClick = event => {
    setList(list.slice().reverse());
  };

  return (
    <div>
      <ul>
        {list.map(item => (
          <li key={item.id}>
            <label>
              <input type="checkbox" />
              {item.name}
            </label>
          </li>
        ))}
      </ul>

      <button type="button" onClick={handleClick}>
        Reverse List
      </button>
    </div>
  );
};

点击按钮,列表重新排序后,背后发生了变化。

TypeScript 复制代码
// 列表最初的样子
[x] Learn React (id = a)
[ ] Learn GraphQL (id = b)

// 点击按钮,列表重新排序后的样子

[ ] Learn GraphQL (id = b)
[x] Learn React (id = a)

在这里,我们使用了 id 作为 key 属性,当然,你也可以使用列表中的其他元素,但前提是这个元素是不可改变的唯一值。

不管怎样,仍然值得注意的是,只要你的列表保持的顺序或大小没有改变,使用索引是可以的。然后,列表中每个项目的位置不会改变------它与索引一样稳定------因此使用索引是可以的。

原文链接:Why do we need a React List Key

相关推荐
太阳伞下的阿呆3 小时前
本地环境vue与springboot联调
前端·vue.js·spring boot
阳光是sunny3 小时前
走进微前端(1)手写single-spa核心原理
前端·javascript·vue.js
烛阴4 小时前
Ceil -- 从平滑到阶梯
前端·webgl
90后的晨仔4 小时前
🔍Vue 模板引用(Template Refs)全解析:当你必须操作 DOM 时
前端·vue.js
90后的晨仔4 小时前
👂 Vue 侦听器(watch)详解:监听数据的变化
前端·vue.js
90后的晨仔4 小时前
深入浅出 Vue 的 computed:不仅仅是“计算属性”那么简单!
前端·vue.js
Nan_Shu_6145 小时前
学习:入门uniapp Vue3组合式API版本(17)
前端·vue.js·学习·uni-app
止观止5 小时前
Remix框架:高性能React全栈开发实战
前端·react.js·前端框架·remix
萌萌哒草头将军5 小时前
🚀🚀🚀 深入探索 Node.js v22.18.0 新特性;默认支持运行 ts 文件了!
前端·typescript·node.js
安心不心安6 小时前
React ahooks——副作用类hooks之useThrottleFn
前端·javascript·react.js