Why is my console not printing the message after every minute passed, does useEffect hook runs only once?

huangapple go评论87阅读模式
英文:

Why is my console not printing the message after every minute passed, does useEffect hook runs only once?

问题

import React, { useState, useEffect } from 'react';

function DigitalClock() {
  const [currentTime, setCurrentTime] = useState(new Date());

  useEffect(() => {
    const interval = setInterval(() => {
      setCurrentTime(new Date());
    }, 1000);

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

  useEffect(() => {
    const second = currentTime.getSeconds();

    if (second === 0) {
      console.log("another minute passed");
    }
  }, [currentTime]);

  const formattedTime = currentTime.toLocaleTimeString();

  return (
    <h2>{formattedTime}</h2>
  );
}

export default DigitalClock;

在这段代码中,你想要在每一分钟过去后使用console.log输出消息,但它只在第一分钟时打印。要解决这个问题,你可以在useEffect的依赖数组中添加currentTime,以确保useEffectcurrentTime更新时被触发,而不仅仅是在组件首次渲染时。

React中的useEffect是用于处理副作用的钩子函数。它接受两个参数,第一个参数是一个函数,包含要执行的副作用代码,第二个参数是一个数组,包含了影响副作用的依赖项。当依赖项发生变化时,useEffect会执行其内部的函数。

在你的代码中,第一个useEffect用于设置一个每秒触发一次的定时器,以更新currentTime的状态。这里没有依赖项,所以它只在组件首次渲染时运行一次,但在后续的渲染中不会重新运行。

第二个useEffect用于检查currentTime的秒数是否为0,并在每分钟时执行console.log。通过在依赖数组中添加currentTime,它会在currentTime变化时重新运行,因此每当分钟数变化时,它都会执行console.log

这样修改后,你的代码应该可以在每分钟过去时执行console.log了。

英文:
import React, { useState, useEffect } from &#39;react&#39;;

function DigitalClock() {
  const[currentTime, setCurrentTime] = useState(new Date());
  useEffect(()=&gt;{
    const interval = setInterval(()=&gt;{
      setCurrentTime(new Date());
    },1000);
    return () =&gt; clearInterval(interval);
  },[]);
  useEffect(()=&gt;{
    const second = currentTime.getSeconds();
    if(second===0){
      console.log(&quot;another minute passed&quot;);
    }
  },[currentTime])
  const formattedTime = currentTime.toLocaleTimeString();
  return(
    &lt;h2&gt;{formattedTime}&lt;/h2&gt;
  )
}

export default DigitalClock;

IN THIS I WANT TO MAKE A CONSOLE.LOG AFTER EVERY MINUTE PASSED, BUT IT ONLY PRINTS THE FIRST MINUTE.

I want to know how to solve this issue, and how does useEffect hooks work in Reactjs.

答案1

得分: 1

I believe you do not need two useEffect to do this. Follow an example:

function DigitalClock() {
  const [currentTime, setCurrentTime] = React.useState(null);

  React.useEffect(() => {
    const interval = setInterval(() => {
      const date = new Date();
      const formattedTime = date.toLocaleTimeString();
      
      setCurrentTime(formattedTime);
    }, 1000);

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

  return <h2>{currentTime}</h2>;
}
英文:

I believe you do not need two useEffect to do this. Follow an example:

function DigitalClock() {
  const [currentTime, setCurrentTime] = React.useState(null);

  React.useEffect(() =&gt; {
    const interval = setInterval(() =&gt; {
      const date = new Date();
      const formattedTime = date.toLocaleTimeString();
      
      setCurrentTime(formattedTime);
    }, 1000);

    return () =&gt; clearInterval(interval);
  }, []);

  return &lt;h2&gt;{currentTime}&lt;/h2&gt;;
}

答案2

得分: 0

你可以修改 useEffect 钩子来检查 seconds 值是否能被 60 整除。你可以使用以下代码:

function DigitalClock() {
  const [currentTime, setCurrentTime] = React.useState(new Date());

  React.useEffect(() => {
    const interval = setInterval(() => {
      setCurrentTime(new Date());
    }, 1000);

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

  React.useEffect(() => {
    const seconds = currentTime.getSeconds();
    if (seconds % 60 === 0 && seconds !== 0) {
      console.log('Another minute passed');
    }
  }, [currentTime]);

  const formattedTime = currentTime.toLocaleTimeString();

  return <h2>{formattedTime}</h2>;
}

ReactDOM.render(<DigitalClock />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>
英文:

you can modify the useEffect hook to check if the seconds value is divisible by 60 .
you can use this code:

<!-- begin snippet: js hide: false console: true babel: true -->

<!-- language: lang-js -->

function DigitalClock() {
  const [currentTime, setCurrentTime] = React.useState(new Date());

  React.useEffect(() =&gt; {
    const interval = setInterval(() =&gt; {
      setCurrentTime(new Date());
    }, 1000);

    return () =&gt; clearInterval(interval);
  }, []);

  React.useEffect(() =&gt; {
    const seconds = currentTime.getSeconds();
    if (seconds % 60 === 0 &amp;&amp; seconds !== 0) {
      console.log(&#39;Another minute passed&#39;);
    }
  }, [currentTime]);

  const formattedTime = currentTime.toLocaleTimeString();

  return &lt;h2&gt;{formattedTime}&lt;/h2&gt;;
}

ReactDOM.render(&lt;DigitalClock /&gt;, document.querySelector(&#39;.react&#39;));

<!-- language: lang-html -->

&lt;script crossorigin src=&quot;https://unpkg.com/react@16/umd/react.development.js&quot;&gt;&lt;/script&gt;
&lt;script crossorigin src=&quot;https://unpkg.com/react-dom@16/umd/react-dom.development.js&quot;&gt;&lt;/script&gt;
&lt;div class=&#39;react&#39;&gt;&lt;/div&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月9日 22:33:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75685990.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定