简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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