[英]React hooks exhaustive-deps infinite loop with async function which uses state
I'm trying to handle an async function to insert data in a database.我正在尝试处理异步 function 以在数据库中插入数据。 Unfortunately the eslint
react-hooks/exhaustive-deps
requires me to add my score
state in the useCallback
.不幸的是,eslint
react-hooks/exhaustive-deps
要求我在 useCallback 中添加我的score
useCallback
。 Although when I add this my app get in an infinite loop state.虽然当我添加这个我的应用程序进入无限循环 state。
When I add eslint-disable-line
on the callback requirements line my code runs perfectly fine.当我在回调要求行上添加
eslint-disable-line
时,我的代码运行得非常好。 Why is this rule in there, and how to solve it the correct way without disabling the eslint rule?为什么这个规则在那里,以及如何在不禁用 eslint 规则的情况下以正确的方式解决它?
import React, { useState, useEffect, useCallback } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { insertData } from 'ducks/data';
const App = () => {
const dispatch = useDispatch();
const sliderData = useSelector((state) => state.data.sliders);
const [score, setScore] = useState(0);
const handleData = useCallback(() => {
dispatch(insertData(score));
}, [dispatch]); // eslint-disable-line
useEffect(() => {
for (const [key, value] of Object.entries(sliderData)) {
const sliders = Object.values(value);
const totalSliderScore = sliders.reduce((a, b) => a + b, 0);
setScore((prevScore) => prevScore += totalSliderScore);
// Last slider in array
if (key === 'lastKey') {
handleData();
}
}
}, [sliderData, handleData]);
return ...
};
export default App;
You can create a reference of the latest score so that it will not cause the loop您可以创建最新分数的参考,这样就不会导致循环
const [score, setScore] = useState(0);
const latestScore = useRef();
const handleData = useCallback(() => {
dispatch(insertData(latestScore));
}, [dispatch,latestScore]); // eslint-disable-line
useEffect(() => {
...
latestScore.current = score
}
}, []);
any state variable used in a useCallback
should be included in the dependency list otherwise you might get stale data of that variable. useCallback 中使用的任何
useCallback
变量都应包含在依赖项列表中,否则您可能会获得该变量的陈旧数据。
const handleData = useCallback(() => {
dispatch(insertData(score));
}, [dispatch, score]);
and why do you need the function handleData
in the dependency list of useEffect
?为什么你需要
handleData
的依赖列表中的useEffect
? Isn't that causing the loop.这不是导致循环。 I think also changing to the following should solve the infinite loop.
我认为也改为以下应该解决无限循环。
useEffect(() => {
for (const [key, value] of Object.entries(sliderData)) {
const sliders = Object.values(value);
const totalSliderScore = sliders.reduce((a, b) => a + b, 0);
setScore((prevScore) => prevScore += totalSliderScore);
// Last slider in array
if (key === 'lastKey') {
handleData();
}
}
}, [sliderData]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.