在反应中使用时刻和时刻时区创建运行时钟

lyc*_*385 3 javascript meteor momentjs reactjs

我正在尝试创建一个呈现滴答作响的时钟的反应组件。我使用 moment 和 moment-timezone 来表示不同的时区。我能够创建一个带有静态时钟的组件(不递增),但我无法创建一个滴答作响的时钟。代码如下:

import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
import moment from 'moment';
import 'moment-timezone';

export default class TimeClock extends React.Component {

    constructor(props) {
      super(props);
      this.state = { time: moment().clone().tz(this.props.timezone).toLocaleString() };
      this.displayTime = this.displayTime.bind(this);
    }

    displayTime(){
        //let now = moment();
        //let location = now.clone().tz(this.props.timezone);
        this.setState({
            time: moment().clone().tz(this.props.timezone).toLocaleString()
        });
        //return location.toLocaleString();
    }
    render(){
        //let now = moment();
        //let location = now.clone().tz(this.props.timezone);
        //let timezone = this.props.timezone;
        return (
            <div>
                <p>{this.props.timezone}</p>
                <p>{setInterval(this.displayTime,1000)}</p>
            </div>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:它是从父组件 App.js 传递的 prop(时区)。

当前代码输出以下内容:

Australia/Melbourne

#######
Run Code Online (Sandbox Code Playgroud)

其中 ####### 表示从 5 或 6 开始并且快速增加的某个数字。

有人可以解释我做错了什么吗?

编辑:发布这个问题后不久,我发现了以下链接(Where to apply my moment() function in a React component?),我适应了我的代码并让它工作,但我不明白为什么我的尝试没有不工作。我是新来的反应。

mdz*_*kon 5

您的代码不会呈现与当前时间相关的任何内容。这行:

<p>{setInterval(this.displayTime,1000)}</p>
Run Code Online (Sandbox Code Playgroud)

不打印当前时间 - 它显示创建的间隔的 ID,因为这是setInterval()函数返回的内容。

因此,首先,您应该根据组件的状态更改此行以显示时间。这可以这样做:

<p>{this.state.time}</p>
Run Code Online (Sandbox Code Playgroud)

您必须做的另一件事是正确创建间隔。在方法中设置它render()不是一个好主意,因为您将创建一个新的间隔

componentDidMount() {
    // Arrow function allows you to use "this" in context of the Component
    this.interval = setInterval(() => {
        this.displayTime();
    }), 1000);
}
Run Code Online (Sandbox Code Playgroud)

(您还应该记住在从视图中删除组件后停用间隔)。