简体   繁体   English

如何使用setInterval在React中重新呈现特定组件还是有另一种方法?

[英]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. 我在React中为时间计数器创建了功能组件。 Everything working fine. 一切正常。 But, component is not re-rendering after every second. 但是,组件不会在每秒后重新渲染。 I am new in React. 我是React的新手。

So, how we can re-render the functional component with setInterval() ? 那么,我们如何使用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 . 如果您是ReactJS的新手,您一定要查看useState文档

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. 要完成这样简单的任务,您可以使用状态更新,React将自动呈现组件。 Without using library like momentjs, vanilla js component will look like this: 不使用像momentjs这样的库,vanilla js组件将如下所示:

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() . 我已使用useState()将全局变量更改为state。
  • I've used useEffect to handle "ComponentDidMount()" it will initialize an interval once. 我已经使用useEffect来处理“ComponentDidMount()”它会初始化一次间隔。
  • Just because it's state now React will listen for it's changes with setTime() and re-render components using that state variable. 只是因为它的状态现在React将使用setTime()监听它的变化并使用该状态变量重新渲染组件。

You can use the useState hook to store the date , 您可以使用useState钩子来存储date

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

You must use the useEffect hook to update the state in a interval, 您必须使用useEffect挂钩来更新间隔中的状态,

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 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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