如何使用 setInterval 构造 useEffect

时间:2021-01-03 23:35:12

标签: javascript reactjs

我遗漏了一些明显但看不到的东西。

updateClock() 实用程序运行并使用日期/时间填充标记,但仅一次。

我知道我必须创建一个 useEffect 并输入更改的状态变量才能重新触发 useEffect,但是我将如何在下面的代码中执行此操作?我是否在错误的地方设置了间隔? setInterval 运行时应该每秒更改什么状态变量?

import { updateClock } from '../../utils/updateClock';

interface LaDateTime {
  yr: string;
  mo: string;
  dt: string;
  hrs: string;
  min: string;
  sec: string;
  day: string;
}

export const Network: FunctionalComponent = () => {
  const { language: lang } = useContext(AppContext);
  const [pageContent, setpageContent] = useState<string | undefined>(undefined);
  const [laDate, setLaDate] = useState<LaDateTime | undefined>(undefined);

  /* *********************************************************************** */
  useEffect(() => {
    const currTime = updateClock();
    setLaDate({ yr: currTime[3], mo: currTime[1], dt: currTime[2], hrs: currTime[4], min: currTime[5], sec: currTime[6], day: currTime[0] });
    const interval = window.setInterval(updateClock, 1000);
    // Clear the interval if/when the component is removed from the DOM
    return () => window.clearInterval(interval);
  }, []);
  /* *********************************************************************** */


  return (
    <div class={style.networkDiv}>
      <div class={style.pageData}>
        {pageContent !== undefined && (
          <Typography>
            <div class={style.topStuff}>
              <div class={style.pageContent}>
                <Markup markup={pageContent} trim={false} type='html' />
              </div>
              <div class={style.clockDiv}>
                <div class={style.timedate}>
                  <a id='day'>{laDate?.day}</a>
                  <br />
                  <a id='mon'>{laDate?.mo}</a>
                  <a id='d'>{laDate?.dt}</a>,<a id='y'>{laDate?.yr}</a>
                  <br />
                  <a id='h'>{laDate?.hrs}</a> :<a id='m'>{laDate?.min}</a>:<a id='s'>{laDate?.sec}</a>
                </div>
              </div>
            </div>

1 个答案:

答案 0 :(得分:2)

您需要更新 setLaDate 回调中的状态(调用 setInterval),这将触发组件的重新渲染。

简单的改变:

useEffect(() => {
  const currTime = updateClock();

  // This is only called one time when the component is mounted. The state
  // is not updated later on each clock update, so your component is not
  // re-rendering:
  setLaDate({
    yr: currTime[3],
    mo: currTime[1],
    dt: currTime[2],
    hrs: currTime[4],
    min: currTime[5],
    sec: currTime[6],
    day: currTime[0],
  });

  // ...despite updateClock being called every second:
  const interval = window.setInterval(updateClock, 1000);

  return () => window.clearInterval(interval);
}, []);

致:

useEffect(() => {
  function tick() {
    const currTime = updateClock();

    // Now you update the state every second as well, which triggers a re-render:
    setLaDate({
      yr: currTime[3],
      mo: currTime[1],
      dt: currTime[2],
      hrs: currTime[4],
      min: currTime[5],
      sec: currTime[6],
      day: currTime[0],
    });
  } 

  tick();

  const interval = window.setInterval(tick, 1000);

  return () => window.clearInterval(interval);
}, []);

此外,我可能会创建一个 useInterval 钩子以便能够以声明方式使用 setInterval,如下所述:https://stackoverflow.com/a/59274004/3723993