[英]useEffect and ESlint exhaustive-deps rule
I'm currently stuck on how to build my logic without having any warning about exhaustive-deps
in my useEffect
.我目前坚持如何构建我的逻辑,而在我的
useEffect
中没有任何关于exhaustive-deps
警告。
My goal is to track navigation (enter page date, leave page date and location) on location change.我的目标是在位置更改时跟踪导航(输入页面日期、离开页面日期和位置)。
I am using useLocation()
of react-router-dom
and useLastLocation()
of react-router-last-location
.我正在使用
react-router-dom
useLastLocation()
useLocation()
react-router-last-location
useLastLocation() 。
const location = useLocation()
const lastLocation = useLastLocation()
const [date, setDate] = React.useState(new Date())
React.useEffect(() => {
const end = new Date()
API.sendData({ start: date, end, location: lastLocation })
setDate(end)
}, [location, lastLocation])
This is working fine but my useEffect
dependencies array should contains date
to not have exhaustive-deps
warning, but adding it, will make infinite loops.这工作正常,但我的
useEffect
依赖项数组应该包含没有exhaustive-deps
警告的date
,但是添加它会产生无限循环。
What is the correct way to do it?正确的方法是什么?
The useState dispatch also allows you to provide a function that accepts the current value as an argument rather than simply a value. useState 调度还允许您提供一个 function,它接受当前值作为参数而不是简单的值。 That way you could avoid the
date
as a dependency.这样您就可以避免将
date
作为依赖项。
const location = useLocation()
const lastLocation = useLastLocation()
const [date, setDate] = React.useState(new Date())
React.useEffect(() => {
setDate((currentDate) => {
const end = new Date();
API.sendData({ start: currentDate, end, location: lastLocation });
return end;
});
}, [location, lastLocation]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.