Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React子容器的Key是很重要的 #72

Open
susouth opened this issue Dec 9, 2019 · 0 comments
Open

React子容器的Key是很重要的 #72

susouth opened this issue Dec 9, 2019 · 0 comments
Labels
JavaScript 跟js相关的面试题 No.2 Reactjs 前端框架三剑客之一的Reactjs面试题目

Comments

@susouth
Copy link
Contributor

susouth commented Dec 9, 2019

📚在线阅读:前端人员需要了解的传值机制 - No.2

key必须传递给从数组中动态创建的所有组件的一个值。它是一个唯一且固定的id,用来识别DOM中的每个组件,也可以让我们区别它是否是同一个组件。使用key可以确保子容器是可保存而且不需要重复创建的,还可以防止奇怪的事情发生。

key跟效率不是很相关,它更与身份有关系(这间接的使效率更好)。随机的赋值或改变值将不能识别身份Paul O’Shannessy

  • 使用对象存在的的唯一值。
  • 在父组件定义key,而不是子组件。
//bad
...
render() {
	<div key={% raw %}{{item.key}}{% endraw %}>{% raw %}{{item.name}}{% endraw %}</div>
}
...

//good
<MyComponent key={% raw %}{{item.key}}{% endraw %}/>
//bad
<MyComponent key={% raw %}{{Math.random()}}{% endraw %}/>

扩展阅读:

@susouth susouth added Reactjs 前端框架三剑客之一的Reactjs面试题目 No.2 JavaScript 跟js相关的面试题 labels Dec 9, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript 跟js相关的面试题 No.2 Reactjs 前端框架三剑客之一的Reactjs面试题目
Projects
None yet
Development

No branches or pull requests

1 participant