【问题标题】:useEffect and ESlint exhaustive-deps ruleuseEffect 和 ESlint 穷举-deps 规则
【发布时间】:2020-08-06 19:41:48
【问题描述】:

我目前正纠结于如何构建我的逻辑,而我的useEffect 中没有关于 exhaustive-deps 的任何警告。

我的目标是在位置更改时跟踪导航(输入页面日期、离开页面日期和位置)。

我正在使用useLocation()react-router-domuseLastLocation()react-router-last-location

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 依赖数组应该包含 date 以没有 exhaustive-deps 警告,但添加它会产生无限循环。

正确的做法是什么?

【问题讨论】:

  • 我可能会看看history.listen() 并注册一个记录页面的函数以及调用该函数以获取所需数据的时间。

标签: reactjs eslint eslint-plugin-react-hooks


【解决方案1】:

useState 调度还允许您提供一个函数,该函数接受当前值作为参数,而不仅仅是一个值。这样您就可以避免将 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]);

【讨论】:

    猜你喜欢
    • 2019-11-20
    • 2021-01-05
    • 1970-01-01
    • 2020-06-22
    • 2020-06-09
    • 2022-01-25
    • 2019-09-29
    • 2022-08-18
    • 2020-06-08
    相关资源
    最近更新 更多