【问题标题】:React setInterval makes unnecessary code to executeReact setInterval 使不必要的代码执行
【发布时间】:2022-01-14 00:19:25
【问题描述】:

我想用 useState、useEffectsetInterval 制作时钟。但是当我运行这段代码时,每秒都会记录一次“hello”。在实际代码中,另一个代码已经到位,而不是我真的只想执行一次的“hello”。我怎么解决这个问题? (使用 useEffect 不是必需的。)

const [clock, setClock] = useState({ year: "", month: "", date: "", hours: "", minutes: "" });

console.log("hello")

useEffect(() => {
  const updateEverySecond = setInterval(() => {
    setClock(getClock());
  }, 1000);
  return () => {
    clearInterval(updateEverySecond);
  };
}, []);

另外,这是getClock()的代码。

function getClock() {
  let now = new Date();
  var monthArray = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);

  const year = String(now.getFullYear());
  const month = String(monthArray[now.getMonth()]);
  const date = String(now.getDate());
  const hours = String(now.getHours());
  const minutes = String(now.getMinutes()).padStart(2, 0);

  return { year, month, date, hours, minutes };
};

【问题讨论】:

    标签: react-hooks setinterval


    【解决方案1】:

    您实际上希望将只想执行一次的代码移动到 useEffect 挂钩中。与您现在使用 useEffect 的方式类似,因为您的依赖项数组(useEffect 的第二个参数)为空,因此当前挂钩中的代码仅执行一次。出于代码组织的目的,您可以简单地创建第二个 useEffect 钩子来替代 console.log("hello"),但不管怎样,最终状态看起来像这样:

    useEffect(() => {
      console.log("hello");
    }, []);
    

    【讨论】:

      【解决方案2】:

      是的,在上面的代码中,hello 每次都会打印出来。这就是 React 函数式组件的工作原理,在每次重新渲染时,它都会再次执行函数内的每一行,这就是为什么要记录 hello

      但是你可以在没有任何状态依赖([])的情况下使用另一个useEffect来实现一次性调用

       useEffect(() => {
          console.log("hello...");
          //this section will only run when component mount (only the first time)
        }, []);
      

      这是一个完整的工作示例 https://codesandbox.io/s/keen-ardinghelli-rmt3l?file=/src/App.js

      【讨论】:

        猜你喜欢
        • 2018-02-23
        • 2017-10-08
        • 1970-01-01
        • 2020-05-11
        • 2012-10-30
        • 2015-07-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多