简体   繁体   中英

why does my setInterval is not working in React app

I'm new to react and I'm trying to create a simple time showing website for practice
I tried using setInterval() but it's not working.

Here's my App.js file

import React from "react";
import "./style.css";

function Clock(props) {
  return (
    <>
      <h2>{props.date.toLocaleTimeString()}</h2>
    </>
  );
}

function App() {
  return (
    <div>
      <Clock date={new Date()} />
    </div>
  );
}

setInterval(App, 1000);  {/* setInterval(Clock, 1000) */}

export default App;

and Index.js file

import React from "react";
import ReactDOM from "react-dom";

import App from "./App";

ReactDOM.render(<App />, document.getElementById("root"));

Calling a functional component alone doesn't do anything unless you put the resulting element into a ReactDOM.render or into another functional component. Your setInterval(App, 1000); is doing nothing.

Have the component get itself to rerender instead.

function App() {
  const [date, setDate] = useState(new Date());
  useEffect(() => {
    setInterval(() => {
      setDate(new Date());
    }, 1000);
  }, []);
  return (
    <div>
      <Clock date={date} />
    </div>
  );
}

Then the single use of ReactDOM.render(<App />, document.getElementById("root")); will result in the clock updating whenever the state changes.

If you ever plan on unmounting the component, it'd also be good to save the interval ID in a variable and return a cleanup function from the effect callback to clear the interval.

  useEffect(() => {
    const intervalId = setInterval(() => {
      setDate(new Date());
    }, 1000);
    return () => clearInterval(intervalId);
  }, []);

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