[英]Eslint exhaustive deps warning in useEffect
In the useEffect
of the component below, I face an ESLint exhaustive-deps warning:在下面组件的
useEffect
中,我遇到了ESLint exhaustive-deps 警告:
ESlint is telling me that I need to include selectedJar
as a dependency, but when I do that the charts load quickly then they all disappear. ESlint 告诉我,我需要将
selectedJar
作为依赖项包含在内,但是当我这样做时,图表会快速加载,然后它们就会全部消失。
I can go on with my development because everything works, but I assume, based on the message from ESlint, that I am doing something wrong.我可以 go 继续我的开发,因为一切正常,但我认为,根据来自 ESlint 的消息,我做错了什么。
Can anyone advise me on how this code should actually look?谁能告诉我这段代码的实际外观?
const Stats: Page = () => {
const [selectedJar, setSelectedJar] = useState("example");
const [jarData, setJarData] = useState<JarChartData>({} as JarChartData);
const router = useRouter();
const jar: string = typeof(router.query.jar) === "string" ? router.query.jar : "";
useEffect(() => {
const getData = async (): Promise<void> => {
setSelectedJar(jar);
const jarData: JarChartData = await getJarData(selectedJar);
setJarData(jarData);
}
getData();
}, [jar]);
return (
<>
something dope
</>
)
You have a potential bug here, in that you both call setSelectedJar
and then use selectedJar
in the same invocation.您在这里有一个潜在的错误,因为您都调用了
setSelectedJar
,然后在同一个调用中使用了selectedJar
。 This isn't likely to do what you want;这不太可能做你想做的事;
selectedJar
is not guaranteed to have the updated value until the next render. selectedJar
不能保证在下一次渲染之前具有更新的值。
Reading your logic, it looks like you want the value you fetch to come from the router all the time, but default to "example"
if there is no value in the router;阅读你的逻辑,看起来你希望你获取的值始终来自路由器,但如果路由器中没有值,则默认为
"example"
; if this is the case, there is no need for the useState
.如果是这种情况,则不需要
useState
。 You can just fetch your jar data whenever the value from router
changes, defaulting it to "example":只要
router
的值发生变化,您就可以获取 jar 数据,默认为“example”:
const router = useRouter();
const [jarData, setJarData] = useState<JarChartData>({} as JarChartData);
const jar: string = typeof(router.query.jar) === "string" ? router.query.jar : "example";
useEffect(() => {
getJarData(jar).then(data => setJarData(data));
}, [jar, setJarData]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.