useEffect 与 setTimeout/setInterval 关闭警报

时间:2021-01-18 16:41:29

标签: reactjs react-hooks settimeout setinterval use-effect

我试图在一段时间后关闭每个警报,但是当我尝试在 useEffect 中调用 setTimeout/Interval 时,我的警报无法正确显示或关闭。就目前而言,总是有一个警报不会被解除,因为 allAlerts 并未持续更新。在 useEffect 停止更新后,如何添加 setTimeout 或 setInterval 以运行我的 checkAlertTimes 函数?

const [filteredAlerts, setFilteredAlerts] = useState()
const checkAlertTimes = () => {
    const currentTime = new Date().getTime()
    setFilteredAlerts(alertsToday.filter(alert => {
      const alertTime = alert.date.getTime()
      const secondsPassed = (currentTime - alertTime) /1000
      if (secondsPassed < 30){return alert}
    }))
  }

  useEffect(() => {
      checkAlertTimes()
  },[allAlerts])

  return (
    <div>{//map through and show alerts}</div>
  )

1 个答案:

答案 0 :(得分:1)

从我看来,您需要这样的东西:

const [filteredAlerts, setFilteredAlerts] = useState();
const checkAlertTimes = () => {
  const currentTime = new Date().getTime();
  setFilteredAlerts(
    alertsToday.filter((alert) => {
      const alertTime = alert.date.getTime();
      const secondsPassed = (currentTime - alertTime) / 1000;
      if (secondsPassed < 30) {
        return alert;
      }
    })
  );
};

useEffect(() => {
  const interval = setInterval(() => {
    checkAlertTimes();
  }, 1000);
  return () => clearInterval(interval);
}, [allAlerts, alertsToday]);

return (
  <div>
    {
      //map through and show alerts
    }
  </div>
);