reactjs - Eroare eslint React: Definiția componentului nu are nume de afișare


Folosind React.memo pentru a învălui componenta mea funcțională, și ea poate rula fără probleme, dar eslint-ul îmi amintește întotdeauna de două erori:

error    Component definition is missing display name  react/display-name

error    'time' is missing in props validation         react/prop-types

Iată codul meu:

type Data = {
  time: number;
};
const Child: React.FC<Data> = React.memo(({ time }) => {
  console.log('child render...');
  const newTime: string = useMemo(() => {
    return changeTime(time);
  }, [time]);

  return (
    <>
      <p>Time is {newTime}</p>
      {/* <p>Random is: {children}</p> */}
    </>
  );
});

Întregul meu cod:

import React, { useState, useMemo } from 'react';

const Father = () => {
  const [time, setTime] = useState(0);
  const [random, setRandom] = useState(0);

  return (
    <>
      <button type="button" onClick={() => setTime(new Date().getTime())}>
        getCurrTime
      </button>
      <button type="button" onClick={() => setRandom(Math.random())}>
        getCurrRandom
      </button>
      <Child time={time} />
    </>
  );
};

function changeTime(time: number): string {
  console.log('changeTime excuted...');
  return new Date(time).toISOString();
}

type Data = {
  time: number;
};
const Child: React.FC<Data> = React.memo(({ time }) => {
  console.log('child render...');
  const newTime: string = useMemo(() => {
    return changeTime(time);
  }, [time]);

  return (
    <>
      <p>Time is {newTime}</p>
      {/* <p>Random is: {children}</p> */}
    </>
  );
});

export default Father;

Răspuns #1

Este pentru că ai o configurație eslint care îți cere să adaugi displayName și propTypes

Fă ceva de genul

const Child: React.FC<Data> = React.memo(({ time }) => {
  console.log('child render...');
  const newTime: string = useMemo(() => {
    return changeTime(time);
  }, [time]);

  return (
    <>
      <p>Time is {newTime}</p>
      {/* <p>Random is: {children}</p> */}
    </>
  );
});

Child.propTypes = {
  time: PropTypes.isRequired
}

Child.displayName = 'Child';

Răspunsul #2

Dacă lucrați cu React și TypeScript, puteți dezactiva regula react/prop-types.

Acest lucru se datorează faptului că interfețele/props-urile din TypeScript sunt suficient de bune pentru a înlocui tipurile de props din React.