Estaba tratando de hacer un reloj usando React (tsx), pero por alguna razón cuando intenté imprimir horas y minutos dentro de un Componente, dijo que no podía encontrar el nombre "hh". También intenté usar 'var' en lugar de 'let' pero da el mismo mensaje.
Aquí está el código:
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;Sus variables date , hh , mm , ..., ampm tienen un ámbito de función, es decir, tienen su contexto dentro de la función setInterval . Entonces, una vez que se ejecuta la función, su contexto se destruye de la memoria. La variable no se encuentra dentro del componente, porque en el momento en que se llama, ya no existe.
Tendría que mover todas sus declaraciones de variables fuera de la función setInterval . Esto se vería algo como esto:
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) { ... }Puede encontrar útil el siguiente enlace: ¿Cuál es el alcance de las variables en JavaScript?
Declaró la variable hh dentro de una función en setInterval, lo que significa que su variable solo es visible en el alcance de la función setInterval, no puede acceder a esto en el alcance principal (que es la función principal).
Lo que podría hacer para corregir este error es agregar un estado y establecer los valores que desea para el estado.
Es mejor crear su función setInterval dentro de useEffect porque no necesita que el componente continúe con el cálculo si está desmontado (obtenga más información sobre el gancho aquí)
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;Puede comprender más sobre el alcance aquí: https://developer.mozilla.org/en-US/docs/Glossary/Scope