1 回答
TA贡献1856条经验 获得超5个赞
您可以使用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>
添加回答
举报