简体   繁体   English

如何在 React.js 中每 5 秒生成一个随机数?

[英]How to generate a random number every 5 seconds in React.js?

I know this question has already been asked and answered, but I can't seem to get the expected output.我知道已经有人提出并回答了这个问题,但我似乎无法得到预期的输出。

let ranNum = 0;

setTimeout(function(){   
  ranNum = Math.floor((Math.random()*100)+1); 
}, 5000);

When I run this my chrome browser keeps generating random numbers over and over until I stop the program.当我运行它时,我的 chrome 浏览器会一遍又一遍地生成随机数,直到我停止程序。 I tried this with setInterval too.我也用 setInterval 试过这个。 What I want to happen is to generate a random number every 5 seconds and add that to another variable in my code.(so this variable should display a different number every five seconds).我想要发生的是每 5 秒生成一个随机数并将其添加到我的代码中的另一个变量中。(所以这个变量应该每 5 秒显示一个不同的数字)。 I'm doing this in my client side - React.js and was wondering if there's another way to do this with react.我正在我的客户端 - React.js 中执行此操作,并且想知道是否有另一种方法可以通过 react 来执行此操作。 Appreciate your help!感谢你的帮助!

You can use a useEffect hook to set the interval and update a state, then display the state您可以使用useEffect钩子设置间隔并更新状态,然后显示状态

 const RandomNumber = () => { const [number, setNumber] = React.useState(0); // add side effect to component React.useEffect(() => { // create interval const interval = setInterval( // set number every 5s () => setNumber(Math.floor(Math.random() * 100 + 1)), 5000 ); // clean up interval on unmount return () => { clearInterval(interval); }; }, []); return <p>{number}</p>; }; ReactDOM.render(<RandomNumber />, document.getElementById("root"));
 <script src="https://unpkg.com/react@17/umd/react.production.min.js" crossorigin></script> <script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js" crossorigin></script> <div id="root"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM