[英]Server Error Error: Too many re-renders. React limits the number of renders to prevent an infinite loop
I am trying to create a simple stopwatch app and getting the following error.我正在尝试创建一个简单的秒表应用程序并收到以下错误。 I have tried the solutions for similar question yet have been unable to identify the real cause and solve it
我已经尝试过类似问题的解决方案,但无法确定真正的原因并解决它
here's my code这是我的代码
import React, { useState, useEffect } from "react"
function Watch() {
const [iter, setiter] = useState(0);
const [running, setRunning] = useState(false);
const [time, setTime] = useState("0:0:0");
const [start, setStart] = useState([]);
const [today, setToday] = useState([]);
useEffect(() => {
let interval;
if (iter == 0) {
var today = new Date()
setStart([today.getHours(), today.getMinutes(), today.getSeconds()])
}
if (running) {
interval = setInterval(() => {
setiter((previter) => previter + 10);
}, 10);
} else if (!running) {
clearInterval(interval);
}
var t = new Date()
setToday([t.getHours(), t.getMinutes(), t.getSeconds()])
return () => clearInterval(interval);
}, [running]);
return (
<div className="stopwatch">
<div className="numbers">
{setTime(running ? (String(today[0] - start[0]) + ':' + String(today[1] - start[1]) + ':' + String(today[2] - start[2])) : time)}
<span>{time}</span>
</div>
<div className="buttons">
<button onClick={() => setRunning(true)}>Start</button>
<button onClick={() => setRunning(false)}>Stop</button>
<button onClick={() => setTime("0:0:0")}>Reset</button>
</div>
</div>
);
};
export default Watch
Please note I am beginner at Next.js this is one of my first project.请注意,我是 Next.js 的初学者,这是我的第一个项目之一。
Please consider this part again.请再考虑这部分。 The error comes from the below line:
错误来自以下行:
<div className="numbers">
{setTime(running ? (String(today[0] - start[0]) + ':' + String(today[1] - start[1]) + ':' + String(today[2] - start[2])) : time)}
<span>{time}</span>
</div>
Please set time while component mounting using useEffect hook rather than now.请在使用 useEffect 挂钩而不是现在安装组件时设置时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.