Necesito ayuda. Estoy tratando de generar un número aleatorio en este código {number} cada segundo. ¿Cómo puedo hacer esto?
Intenté esto, genera el número al azar pero no lo actualiza cada segundo.
número de variable;
(function repeat() { number = Math.floor((Math.random()*100)+1); setTimeout(repeat, 1000); setInterval(repeat, 1000); })();importar React desde 'reaccionar' importar estilo, {fotogramas clave} de 'componentes con estilo'
clase ProgressBar extiende React.Component {
render() { const { text } = this.props const ProgressContainer = styled.div` margin-bottom: 25px; ` const Text = styled.span` font-size: 17px; font-family: Poppins; color: #fff; ` const Value = styled.span` font-size: 17px; font-family: Poppins; color: #fff; float: right; ` const ColorAnimation = keyframes` 0% {background: #04e5e5;} 10% {background: #f37055;} 20% {background: #ef4e7b;} 30% {background: #a166ab;} 40% {background: #5073b8;} 50% {background: #04e5e5;} 60% {background: #07b39b;} 70% {background: #6fba82;} 80% {background: #5073b8;} 90% {background: #1098ad;} 100% {background: #f37055;} ` const Progress = styled.div` height: 5px; border-radius: 2.5px; margin-top: 10px; transition: 2s; animation: ${ColorAnimation} 10s infinite alternate; ` return( <ProgressContainer> <Text>{text}</Text> <Value>{number}%</Value> <Progress style={{width: `${number}%`}}></Progress> </ProgressContainer> ) }Gracias
Usando el gancho useEffect , puede crear el setInterval necesario y limpiarlo cuando el componente se desmonte:
useEffect(() => { const interval = setInterval(() => { ** code for random number goes here ** }, 1000); return () => clearInterval(interval); }, []); Para que el componente se vuelva a renderizar cada vez que cambie el número aleatorio, puede utilizar el useState :
const [randomNumber, setRandomNumber] = useState(null);Poniendolo todo junto:
import React, {useState, useEffect} from "react"; const Container = () => { const [randomNumber, setRandomNumber] = useState(null) useEffect(() => { const interval = setInterval(() => { setRandomNumber(Math.floor((Math.random()*100)+1)) }, 1000); return () => clearInterval(interval); }, []); return (<div>{randomNumber}</div>) }Puedes verlo en acción en este JSFiddle .