React hooks学习小结(一)—— key

1. key render

the key lets React identify the item throughout its lifetime.
(React通过key对item识别跟踪,是唯一标识符)

tips:保证稳定且唯一

  • 不要使用index作为key。如果item被插入、删除或者数组重新排序,渲染项目的顺序会随着时间的推移而改变
  • 不要即时生成key,例如key={Math.random()}。
    • key不稳定,键在渲染之间永远不会匹配,从而导致每次都重新创建所有组件和 DOM,性能差
    • 每次渲染key都会变,丢失列表项内的任何用户输入,例如输入框输入一次就失去焦点。

1. 1 <Fragment> (<>...</>)

空的 JSX 标签<></>是简写,Fragments disappear from the DOM

return (
    <>
      <OneChild />
      <AnotherChild />
    </>
)

当你在循环中渲染多个元素时,你需要为每个元素分配一个key。
如果你想传递key给一个片段,你不能使用<>…</>语法。您必须显式导入Fragment和’react’渲染<Fragment key={yourKey}>...</Fragment>。

import {
    
     Fragment } from 'react';

const posts = [
  {
    
     id: 1, title: 'An update', body: "It's been a while since I posted..." },
  {
    
     id: 2, title: 'My new blog', body: 'I am starting a new blog!' }
];

export default function Blog() {
    
    
  return posts.map(post =>
    <Fragment key={
    
    post.id}>
      <h1>{
    
    post.title}</h1>
      <article><p>{
    
    post.body}</p></article>
    </Fragment>
  );
}

1.2 为什么需要包裹多个 JSX 标签?

JSX 在底层被转换为普通的 JavaScript 对象。如果不将它们包装到数组中,则不能从函数返回两个对象。这解释了为什么不能返回两个 JSX 标签,而是将它们包装到另一个标签或片段中。

猜你喜欢

转载自blog.csdn.net/qq_29493173/article/details/128874277