React hooks learning summary (1) - key

1. key render

the key lets React identify the item throughout its lifetime.
(React identifies and tracks the item through the key, which is a unique identifier)

tips: ensure stability and uniqueness

  • Don't use index as key . The order of rendered items will change over time if items are inserted, removed or the array is reordered
  • Do not generate keys on the fly , eg key={Math.random()}.
    • The key is unstable, the key will never match between renders, causing all components and DOM to be recreated every time, poor performance
    • The key will change every time it is rendered, and any user input in the list item will be lost. For example, the input box will lose focus once it is entered.

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

Empty JSX tags <></> are shorthand, Fragments disappear from the DOM

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

When you render multiple elements in a loop, you need to assign a key to each element.
If you want to pass the key to a fragment, you cannot use the <>...</> syntax. You have to explicitly import Fragment and 'react' render<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 Why do I need to wrap multiple JSX tags?

Under the hood, JSX is converted to plain JavaScript objects. You cannot return two objects from a function without wrapping them into an array. This explains why you can't return two JSX tags, but wrap them in another tag or fragment.

Guess you like

Origin blog.csdn.net/qq_29493173/article/details/128874277