[英]useEffect dependency array and ESLint exhaustive-deps rule
[英]useEffect and ESlint exhaustive-deps rule
我目前坚持如何构建我的逻辑,而在我的useEffect
中没有任何关于exhaustive-deps
警告。
我的目标是在位置更改时跟踪导航(输入页面日期、离开页面日期和位置)。
我正在使用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])
这工作正常,但我的useEffect
依赖项数组应该包含没有exhaustive-deps
警告的date
,但是添加它会产生无限循环。
正确的方法是什么?
useState 调度还允许您提供一个 function,它接受当前值作为参数而不是简单的值。 这样您就可以避免将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.