-
Notifications
You must be signed in to change notification settings - Fork 3
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,其作用是什么 #1
Comments
使用index 作为key 可能会出现的问题 https://juejin.cn/post/6967626390380216334#heading-2 更多 demo {this.state.data.map((v,index) => <Item key={index} v={v} />)}
// 开始时:['a','b','c']=>
<ul>
<li key="0">a <input type="text"/></li>
<li key="1">b <input type="text"/></li>
<li key="2">c <input type="text"/></li>
</ul>
// 数组重排 -> ['c','b','a'] =>
<ul>
<li key="0">c <input type="text"/></li>
<li key="1">b <input type="text"/></li>
<li key="2">a <input type="text"/></li>
</ul> |
不加 key 再渲染时会更快。 验证,渲染 10_000 个 总共打印两次结果,第一次componentDidMount时更新 state,第二次间隔 1 秒更新 state 再打印。 import React, { Component } from 'react';
import uuid from 'uuid/v1';
let time = 0
class App extends Component {
state = {
list: []
}
componentDidMount() {
const list = Array.from({length: 1000}).fill(null).map(() => ({
value: uuid(),
key: uuid()
}));
this.setState({list})
setTimeout( () => {
const list = Array.from({length: 1000}).fill(null).map(() => ({
value: uuid(),
key: uuid()
}), 1000);
this.setState({list})
})
}
componentWillUpdate() {
time = +Date.now()
}
componentDidUpdate() {
console.log(+Date.now() - time)
}
render() {
const {list} = this.state;
return (
<div className="App">
<ul>
{list.map((item,idx) => (
<li>{item.value}</li>
// <li key={item.key}>{item.value}</li>
))}
</ul>
</div>
);
}
} 不加 key 的结果: 加 key 的结果: |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
使用key是react性能优化的手段,在一系列数据最前面插入元素,如果没有key的值,则所有的元素都需要进行更换,而有key的情况只需要将最新元素插入到前面,不涉及删除操作
详解diff
在使用key的时候应保证:
key 应该是唯一的
key不要使用随机值(随机数在下一次 render 时,会重新生成一个数字)
避免使用 index 作为 key
react
React 源码深度解读(十):Diff 算法详解
解析:Daily-Interview-Question/issues/1
warning.js:33 Warning: Each child in an array or iterator should have a unique "key" prop.
。Child keys must be unique; when two children share a key, only the first child will be used.
第一遍渲染时 key 重复的 item ,在第二遍渲染时保留了下来。---->(React 在渲染列表时,列表元素的 Key 重复了会怎样?)demohttps://www.jianshu.com/p/e639dbc325ef
The text was updated successfully, but these errors were encountered: