javascript - ReactJS 中键的意义是什么?

标签 javascript reactjs

我想了解如果我不在动态添加的组件中使用键会发生什么。我删除了 key ,它渲染时没有任何问题,只是给出了有关 key 使用的警告消息。有人可以举例说明如果我们不使用 key 会产生什么后果吗?

最佳答案

键帮助 React 识别哪些项目已更改、添加或删除。应为数组内的元素赋予键,以便为元素提供稳定的标识:

示例:

const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
  <li key={number.toString()}>
    {number}
  </li>
);

TL;DR 在渲染动态子项时使用唯一且恒定的键,否则会发生奇怪的事情。

One of the tricky aspects I've found during the few weeks I've been using React.js is to understand the key property you're expected to pass to a component when it's part of an array of children. It's not that you have to specify this property, things will work most of the time apart from getting this warning on the console:

Each child in an array should have a unique "key" prop. Check the render method of undefined. By reading the linked documentation it can be easy to not see the implications of this affirmation:

When React reconciles the keyed children, it will ensure that any child with key will be reordered (instead of clobbered) or destroyed (instead of reused). At first it looked to me it was all about performance but, as Paul O’Shannessy pointed, it's actually about identity.

The key here is to understand not everything in the DOM has a representation in React "Virtual DOM" and, because direct manipulations of the DOM (like a user changing an value or a jQuery plugin listening an element) are unnoticed by React, not using unique and constant keys will end up with React recreating the DOM node of a component when the key is not constant (and losing any untracked state in the node) or reusing a DOM node to render another component when the key is not unique (and tying its state to this other component).

Here you have a live demo showing how awful the results are:

http://jsfiddle.net/frosas/S4Dju/

Just add an item, change it, add more items and see what happens.

还有see

Source

关于javascript - ReactJS 中键的意义是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42801343/

相关文章:

javascript - 滚动一点点时跳转到部分 - React

javascript - 为什么 node.js 生成器没有按预期工作?

javascript - 重定向控制

php - Javascript 无法与 PHP echo 语句一起使用

javascript - 通过子级的回调属性更新父级的状态(React.js)

reactjs - 从 useEffect 调用 dispatch

javascript - 在 Chrome 54 中扩展内置元素时无法创建自定义元素

javascript - 双向无限滚动

node.js - useNavigate - 无效 Hook 调用。钩子(Hook)只能在函数组件的内部调用

javascript - 响应美化 URL