每秒更新React组件 [英] Update React component every second

查看:184
本文介绍了每秒更新React组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩React,并且有以下时间组件只是将 Date.now()呈现给屏幕:

I have been playing around with React and have the following time component that just renders Date.now() to the screen:

import React, { Component } from 'react';

class TimeComponent extends Component {
  constructor(props){
    super(props);
    this.state = { time: Date.now() };
  }
  render(){
    return(
      <div> { this.state.time } </div>
    );
  }
  componentDidMount() {
    console.log("TimeComponent Mounted...")
  }
}

export default TimeComponent;

让这个组件每秒更新以重新绘制时间的最佳方法是什么一个React透视图?

What would be the best way to get this component to update every second to re-draw the time from a React perspective?

推荐答案

你需要使用 setInterval 来触发更改,但您还需要在组件卸载时清除计时器,以防止它留下错误和泄漏内存:

You need to use setInterval to trigger the change, but you also need to clear the timer when the component unmounts to prevent it leaving errors and leaking memory:

componentDidMount() {
  this.interval = setInterval(() => this.setState({ time: Date.now() }), 1000);
}
componentWillUnmount() {
  clearInterval(this.interval);
}

这篇关于每秒更新React组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆