Yeo*_*_Li 2 typescript reactjs eslint
使用Reac.memo包裹我的功能组件,它可以流畅运行,但eslint总是让我想起了两个错误:
error Component definition is missing display name react/display-name
error 'time' is missing in props validation react/prop-types
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
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> */}
</>
);
});
Run Code Online (Sandbox Code Playgroud)
我的整个代码:
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;
Run Code Online (Sandbox Code Playgroud)
这是因为您有 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';Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6216 次 |
| 最近记录: |