TypeScript - 找不到名称“变量”在反应中

发布于 2025-01-11 01:45:19 字数 1136 浏览 1 评论 0原文

我正在尝试使用 React (tsx) 制作时钟,但由于某种原因,当我尝试在组件内打印小时和分钟时,它说找不到名称“hh”。我也尝试使用“var”而不是“let”,但它给出了相同的消息。

这是代码:

import styled from "styled-components";

const Clock = () => {
  setInterval(() => {
    let date = new Date();
    let hh: string | number = date.getHours();
    let mm = date.getMinutes();
    let day = date.getDate();
    let dayweek = date.getDay();
    let month = date.getMonth();
    let year = date.getFullYear();
    let ampm;

    if (hh >= 12) {
      hh = hh - 12;
      ampm = "PM";
    } else {
      ampm = "AM";
    }

    if (hh == 0) {
      hh = 12;
    }
    if (hh < 10) {
      hh = `0${hh}`;
    }
  }, 1000);
  return (
    <ClockContainer>
      <ClockTime>{hh}</ClockTime>
    </ClockContainer>
  );
};

const ClockContainer = styled.div`
  flex: 0.3;
  display: flex;
  align-items: center;
  font-family: Poppins;
`;
const ClockTime = styled.div`
  font-size: 98px;
  cursor: default;
  user-select: none;
  text-shadow: 3px 3px 8px #00000033;
  color: var(--fontColor);
  transition: all 500ms ease-in-out;
`;

export default Clock;

I was trying making a clock using React (tsx), but for some reason when I tried printing hours and minutes inside a Component, It said it cannot find the name "hh". I tried also using 'var' instead of 'let' but it gives the same message.

Here's the code:

import styled from "styled-components";

const Clock = () => {
  setInterval(() => {
    let date = new Date();
    let hh: string | number = date.getHours();
    let mm = date.getMinutes();
    let day = date.getDate();
    let dayweek = date.getDay();
    let month = date.getMonth();
    let year = date.getFullYear();
    let ampm;

    if (hh >= 12) {
      hh = hh - 12;
      ampm = "PM";
    } else {
      ampm = "AM";
    }

    if (hh == 0) {
      hh = 12;
    }
    if (hh < 10) {
      hh = `0${hh}`;
    }
  }, 1000);
  return (
    <ClockContainer>
      <ClockTime>{hh}</ClockTime>
    </ClockContainer>
  );
};

const ClockContainer = styled.div`
  flex: 0.3;
  display: flex;
  align-items: center;
  font-family: Poppins;
`;
const ClockTime = styled.div`
  font-size: 98px;
  cursor: default;
  user-select: none;
  text-shadow: 3px 3px 8px #00000033;
  color: var(--fontColor);
  transition: all 500ms ease-in-out;
`;

export default Clock;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

耳根太软 2025-01-18 01:45:19

您的变量 datehhmm、...、ampm 是函数范围的,即它们有自己的setInterval 函数中的上下文。因此,一旦函数被执行,它们的上下文就会从内存中被销毁。在组件内部找不到该变量,因为在调用它时,它已不存在。

您需要将所有变量声明移至 setInterval 函数之外。这看起来像这样:

const Clock = () => {
  let date;
  let hh: string | number;
  let mm;
  let day;
  let dayweek;
  let month;
  let year;
  let ampm;

  setInterval(() => {
    date = new Date();
    hh = date.getHours();
    mm = date.getMinutes();
    day = date.getDate();
    dayweek = date.getDay();
    month = date.getMonth();
    year = date.getFullYear();

    // remaining code would remain as it is
    if (hh >= 12) {
       ...
}

您可能会发现以下链接很有用:什么JavaScript 中变量的作用域是什么?

Your variables date, hh, mm, ..., ampm are function-scoped, i.e. they have their context within the setInterval function. So, once the function is executed, their context gets destroyed from the memory. The variable is not found inside the component, because by the time it is called, it no longer exists.

You would need to move all your variable declarations outside the setInterval function. This would look something like this:

const Clock = () => {
  let date;
  let hh: string | number;
  let mm;
  let day;
  let dayweek;
  let month;
  let year;
  let ampm;

  setInterval(() => {
    date = new Date();
    hh = date.getHours();
    mm = date.getMinutes();
    day = date.getDate();
    dayweek = date.getDay();
    month = date.getMonth();
    year = date.getFullYear();

    // remaining code would remain as it is
    if (hh >= 12) {
       ...
}

You may find the following link useful: What is the scope of variables in JavaScript?

生生漫 2025-01-18 01:45:19

您在 setInterval 上的函数内声明了 hh 变量,这意味着您是变量,它仅在 setInterval 函数的范围内可见,您无法在主范围(即主函数)上访问它。

要修复此错误,您可以执行以下操作:添加一个状态并为该状态设置所需的值。

最好在 useEffect 中创建 setInterval 函数,因为如果组件已卸载,则不需要组件继续计算 (在此处了解有关挂钩的更多信息)

import styled from "styled-components";
import { useEffect, useState } from "react";

const Clock = () => {
  const [hours, setHours] = useState(0);

  useEffect(() => {
    const intervalId = setInterval(() => {
      let date = new Date();
      let hh = date.getHours();
      let mm = date.getMinutes();
      let day = date.getDate();
      let dayweek = date.getDay();
      let month = date.getMonth();
      let year = date.getFullYear();
      let ampm;

      if (hh >= 12) {
        hh = hh - 12;
        ampm = "PM";
      } else {
        ampm = "AM";
      }

      if (hh == 0) {
        hh = 12;
      }
      if (hh < 10) {
        hh = `0${hh}`;
      }

      setHours(hh);
    }, 1000);

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

  return (
    <ClockContainer>
      <ClockTime>{hours}</ClockTime>
    </ClockContainer>
  );
};

const ClockContainer = styled.div`
  flex: 0.3;
  display: flex;
  align-items: center;
  font-family: Poppins;
`;
const ClockTime = styled.div`
  font-size: 98px;
  cursor: default;
  user-select: none;
  text-shadow: 3px 3px 8px #00000033;
  color: var(--fontColor);
  transition: all 500ms ease-in-out;
`;

export default Clock;

您可以在此处了解有关范围的更多信息:
https://developer.mozilla.org/en-US/docs/Glossary/范围

You declared the hh variable inside a function on setInterval, which means you're variable it's only visible on the scope of setInterval function, you cannot access this on the main scope (which is the main function).

What you could do to fix this error is add a state and set the values that you want to the state.

It's better to create your setInterval function inside a useEffect because you don't need that the component continues with the calculation if it's unmounted (learn more about the hook here)

import styled from "styled-components";
import { useEffect, useState } from "react";

const Clock = () => {
  const [hours, setHours] = useState(0);

  useEffect(() => {
    const intervalId = setInterval(() => {
      let date = new Date();
      let hh = date.getHours();
      let mm = date.getMinutes();
      let day = date.getDate();
      let dayweek = date.getDay();
      let month = date.getMonth();
      let year = date.getFullYear();
      let ampm;

      if (hh >= 12) {
        hh = hh - 12;
        ampm = "PM";
      } else {
        ampm = "AM";
      }

      if (hh == 0) {
        hh = 12;
      }
      if (hh < 10) {
        hh = `0${hh}`;
      }

      setHours(hh);
    }, 1000);

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

  return (
    <ClockContainer>
      <ClockTime>{hours}</ClockTime>
    </ClockContainer>
  );
};

const ClockContainer = styled.div`
  flex: 0.3;
  display: flex;
  align-items: center;
  font-family: Poppins;
`;
const ClockTime = styled.div`
  font-size: 98px;
  cursor: default;
  user-select: none;
  text-shadow: 3px 3px 8px #00000033;
  color: var(--fontColor);
  transition: all 500ms ease-in-out;
`;

export default Clock;

You can understand more about scope here:
https://developer.mozilla.org/en-US/docs/Glossary/Scope

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文