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 / Vue 项目时为什么要在列表组件中写 key,其作用是什么? #2

Open
yidafu opened this issue Apr 19, 2019 · 2 comments

Comments

@yidafu
Copy link
Owner

yidafu commented Apr 19, 2019

解析:Daily-Interview-Question/issues/1

@yidafu
Copy link
Owner Author

yidafu commented Apr 19, 2019

不加 key 再渲染时会更快。

验证,渲染 10_000 个<li>标签,在componentWillUpdate标记 render 开始时间,componentDidUpdate生命周期里打印时间差。

总共打印两次结果,第一次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 的结果:

image

加 key 的结果:

image

@yidafu
Copy link
Owner Author

yidafu commented May 31, 2019

同时满足以下条件时可以使用数组索引作为 key 值:

  • 数组是静态的:不经过计算,也不会改变;
  • 数组项没有 id;
  • 数组不做排序或者过滤操作。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant