如何在React中使用setInterval()?——React可运行时钟组件实现求助
Fixing Your React Clock with
setInterval Got it, let's get your clock updating every second properly! The issue with your current code is two-fold:
- You're only calculating the time once when the component renders, not triggering re-renders to refresh it
- Putting
setIntervaldirectly in therendermethod would create a new timer every time the component re-renders, which is a memory leak waiting to happen
Here's the correct approach using React class component lifecycle methods:
Step-by-Step Explanation
- Store the current time in component state: React re-renders components when state or props change, so we need to hold the time in state to trigger updates.
- Set up the timer in
componentDidMount: This lifecycle method runs once after the component mounts, making it the perfect spot to start our interval. - Clear the timer in
componentWillUnmount: Always clean up timers when the component unmounts to avoid lingering background processes. - Update state in the
tickmethod: Changing state will tell React to re-render the component with the latest time.
Modified Code
import React from "react"; import ReactDOM from "react-dom"; import "./styles.css"; class App extends React.Component { // Initialize state with the current time state = { currentTime: new Date().toLocaleTimeString() }; componentDidMount() { // Set up the interval to call tick every 1000ms (1 second) this.timerID = setInterval(() => this.tick(), 1000); } componentWillUnmount() { // Clear the interval when the component unmounts clearInterval(this.timerID); } tick() { // Update state with the new time, triggering a re-render this.setState({ currentTime: new Date().toLocaleTimeString() }); } render() { // Display the time from state return <h1>{this.state.currentTime}</h1>; } } export default App;
Key Notes
- We assign the interval ID to
this.timerIDso we can reference it later to clear the timer. - Using an arrow function in
setInterval(() => this.tick()) ensures thatthisrefers to the component instance whentickis called. - If you ever want to switch to functional components (the modern React standard), you could use the
useStateanduseEffecthooks instead—but this keeps things consistent with your original class component setup.
内容的提问来源于stack exchange,提问作者user17880803
相关产品推荐
相关产品推荐

