【问题标题】:React eslint error:Component definition is missing display nameReact eslint报错:组件定义缺少显示名称
【发布时间】:2020-07-28 11:19:34
【问题描述】:

使用Reac.memo包裹我的功能组件,可以流畅运行,但是eslint总是提示我两个错误:

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

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

这是我的代码:

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> */}
    </>
  );
});

我的整个代码:

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;

【问题讨论】:

标签: reactjs typescript eslint


【解决方案1】:

这是因为你有 eslint 配置,需要你添加 displayName 和 propTypes

做类似的事情

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';

【讨论】:

    【解决方案2】:

    如果您正在使用 React 和 TypeScript,您可以关闭 react/prop-types 规则。

    这是因为 TypeScript 接口/道具足以替代 React 的道具类型。

    【讨论】:

    • Typescript 和 PropTypes 有不同的用途。 Typescript 在编译时验证类型,而 PropTypes 在运行时检查。
    • @SomeoneSpecial 是的,你是对的。我的主要目的是让 OP 关闭该规则,因为他们似乎没有使用道具类型。我同意我的回答措辞不当。
    猜你喜欢
    • 2020-06-19
    • 2019-03-30
    • 2021-08-16
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 2019-09-01
    相关资源
    最近更新 更多