简体   繁体   中英

How to re-render a particular component in React with setInterval or there is another way?

I have created the functional component in React for time counter. Everything working fine. But, component is not re-rendering after every second. I am new in React.

So, how we can re-render the functional component with setInterval() ?

import React from 'react'
import withStyle from 'react-jss'


const counterStyle = {
    counter:{
        color:'#FFFFFF'
    }
}

let date = new Date();    
let todayDate = date.getDate();
let hours = date.getHours()
let minutes = date.getMinutes();
let second = date.getUTCSeconds();    

const timerDisplay = () => {
     date = new Date();    
     todayDate = date.getDate();
     hours = date.getHours()
     minutes = date.getMinutes();
     second = date.getUTCSeconds();    
}

const TimeCounter = ({classes}) => {
    setInterval(() => {
        timerDisplay()
    }, 1000);
    return(
        <div className={classes.counter}>
            <h1>{`${hours} : ${minutes} : ${second} : ${todayDate}`}</h1>
        </div>
    )
}

export default withStyle(counterStyle)(TimeCounter);

If you are new to ReactJS you should definitely take a look at the useState documentation .

Your approach to a react component is wrong actually. To accomplish such simple task you can use state updates and React will automatically render the component. Without using library like momentjs, vanilla js component will look like this:

import React, { useState, useEffect } from 'react'
import withStyle from 'react-jss'

const TimeCounter = ({classes}) => {
    const [time, setTime] = useState(new Date())

    useEffect(() => {
        setInterval(() => {
            setTime(new Date())
        }, 1000);
    }, []);

    return(
        <div className={classes.counter}>
            <h1>{`
                ${time.getHours()} : 
                ${time.getMinutes()} : 
                ${time.getUTCSeconds()} : 
                ${time.getDate()}
            `}</h1>
        </div>
    )
}

export default withStyle(counterStyle)(TimeCounter);
  • I've changed global variable to state using useState() .
  • I've used useEffect to handle "ComponentDidMount()" it will initialize an interval once.
  • Just because it's state now React will listen for it's changes with setTime() and re-render components using that state variable.

You can use the useState hook to store the date ,

const [timer, setTimer] = useState(new Date());

You must use the useEffect hook to update the state in a interval,

useEffect(() => {
   const interval = setInterval(() => {
      console.log('This will run every second!');
      setTimer(new Date());
   }, 1000);

   // This is important, you must clear your interval when component unmounts
   return () => clearInterval(interval);

}, [])  // [] is for to execute `useEffect` only once as `componentWillMount`

Demo

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