• ⑦ 列表 & key


    1. 渲染多个组件

    const numbers = [1, 2, 3, 4, 5]
    const listItems = numbers.map(number => <li>{ number }</li>)
    
    ReactDOM.render(
      <ul>{ listItems }</ul>,
      document.getElementById('root')
    )
    

    2. 基础列表组件

    function NumberList(props) {
      const numbers = props.numbers
      const listItems = numbers.map(number => <li>{ number }</li>)
    
      return (
        <ul>{ listItems }</ul>
      )
    }
    
    const numbers = [1, 2, 3, 4, 5]
    ReactDOM.render(
      <NumberList numbers={ numbers } />,
      document.getElementById('root')
    )
    // a key should be provided for list items
    
    • 给每个列表元素分配一个 key 属性
    function NumberList(props) {
      const numbers = props.numbers
      const listItems = numbers.map(number => 
        <li key={ number.toString() }>{ number }</li>
      )
    
      return (
        <ul>{ listItems }</ul>
      )
    }
    
    const numbers = [1, 2, 3, 4, 5]
    ReactDOM.render(
      <NumberList numbers={ numbers } />,
      document.getElementById('root')
    )
    

    3. key

    • 一个元素的 key 最好是这个元素在列表中拥有的一个独一无二的字符串

    • 通常,我们使用数据中的 id 来作为元素的 key

    • 当元素没有确定 id 的时候,万不得已你可以使用元素索引 index 作为 key

    如果列表项目的顺序可能会变化,不建议使用索引来用作 key 值,因为这样做会导致性能变差,还可能引起组件状态的问题

    3.1 用 key 提取组件

    • 元素的 key 只有放在就近的数组上下文中才有意义
    function ListItem(props) {
      // 正确!这里不需要指定 key:
      return <li>{props.value}</li>;
    }
    
    function NumberList(props) {
      const numbers = props.numbers;
      const listItems = numbers.map(number =>
        // 正确!key 应该在数组的上下文中被指定
        <ListItem key={ number.toString() } value={ number } />
      );
      return (
        <ul>
          { listItems }
        </ul>
      );
    }
    
    const numbers = [1, 2, 3, 4, 5];
    ReactDOM.render(
      <NumberList numbers={ numbers } />,
      document.getElementById('root')
    );
    
    • key 只是在兄弟节点之间必须唯一
    3.2 key 会传递信息给 React ,但不会传递给你的组件
    const content = posts.map((post) =>
      <Post
        key={post.id}
        id={post.id}
        title={post.title} />
    );
    // Post 组件可以读出 `props.id`,但是不能读出 `props.key`
    
  • 相关阅读:
    ThreadPoolExecutor的corePoolSize、maximumPoolSize和poolSize
    ThreadPoolExecutor线程池的一个面试题
    SpringBoot 集成Jedis操作set
    死磕JVM之类中各部分的加载顺序
    ThreadLocal为什么会内存泄漏
    有趣的RPC理解
    MQ如何解决消息的顺序性
    Collections.sort排序
    对象的内存分析
    类与对象的分析
  • 原文地址:https://www.cnblogs.com/pleaseAnswer/p/15411295.html
Copyright © 2020-2023  润新知