reactjs - Hur konfigurerar jag eslint-regler för att globalt ignorera react-hooks/exhaustive-deps?
Jag har en React-komponent med en useEffect-hook som ser ut så här:
const LocationEditor: React.FC<SectionEditorProps> = (props) => {
const [section, setSection] = useState({...(props.section as Location)});
useEffect(() => {
props.onChange(section);
}, [section]);
Jag får denna varning när jag kör projektet:
React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array. However, 'props' will change when *any* prop changes, so the preferred fix is to destructure the 'props' object outside of the useEffect call and refer to those specific props inside useEffect react-hooks/exhaustive-deps
Så jag försökte ändra komponenten för att se ut så här, med destrukturering av props:
const LocationEditor: React.FC<SectionEditorProps> = ({section, onClickCancel, onClickSave, onChange}) => {
const [tmpSection, setSection] = useState({...(section as Location)});
useEffect(() => {
onChange(tmpSection);
}, [tmpSection]);
Om jag lägger till denna kommentar före beroende-arrayen kan jag få varningen att försvinna:
// eslint-disable-next-line react-hooks/exhaustive-deps
Men när jag lägger till blocket nedan i eslintConfig i package.json verkar det inte göra någonting:
{
"plugins": [
"react-hooks"
],
"rules": {
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "off"
}
}
Jag ser att vissa personer pratar om att använda .eslinrc-filen, men jag trodde att man också kunde konfigurera regler globalt i package.json och jag kan inte hitta den filen i mitt projekt.
Är det något jag missar här?
Svar #1
Att inaktivera det globalt rekommenderas inte eftersom det hjälper till att påpeka potentiella buggar. Innan du inaktiverar regeln lokalt, kontrollera noggrant att den inte pekar på en möjlig bugg.
Du kan stänga av det lokalt med:
// eslint-disable-next-line react-hooks/exhaustive-deps
