ReactJS实时日期之间的时间

时间:2018-04-28 23:13:17

标签: reactjs momentjs real-time

我试图找出如何制作一个实时计数器,这样可以在不刷新页面的情况下增加秒数。这是我的代码如下。我很高兴使用ReactJS任何提示/帮助将不胜感激。感谢..

import sys, traceback
import os
import cv2
from PyQt5 import QtCore
from PyQt5.QtCore import *
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QDialog, QFileDialog, QApplication, QComboBox, QStackedWidget
from PyQt5.uic import loadUi

class ezNPR(QDialog):
    def __init__(self):
        super(ezNPR, self).__init__()
        loadUi('ezNPRApp.ui', self)
    self.image = None
    self.AppStackedWidget.setCurrentIndex(0)
    self.ExitPushButton.clicked.connect(QDialog.close)
    self.ImagePushButton.clicked.connect(lambda: self.AppStackedWidget.setCurrentIndex(0))
    self.SignaturePushButton.clicked.connect(lambda: self.AppStackedWidget.setCurrentIndex(1))
    self.HelpPushButton.clicked.connect(lambda: self.AppStackedWidget.setCurrentIndex(2))
    self.SelectImage.clicked.connect(self.load_clicked)

@pyqtSlot()
def load_clicked(self):
    fname, filter = QFileDialog.getOpenFileName(self, "Open File", os.getenv("HOME"))
    try:
        if fname:
            self.image = cv2.imread(fname)
            #cv2.imshow("First Image", self.image)
            self.display_image()
        else:
            print('No image selected')
            # msg = QtWidgets.QMessageBox()
            # msg.setText("Invalid image type selected. Please select a new image.")
            # msg.setInformativeText("You must select a BMP, JPG, PNG, or TIFF")
            # msg.setWindowTitle("Error Loading Image")
            # msg.setStandardButtons(msg.Ok)
    finally:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        print("*** print_tb:")
        traceback.print_tb(exc_traceback, limit=5, file=sys.stdout)

def display_image(self):
    displayorig = self.image
    dih, diw = displayorig.shape[:2]
    if dih > diw:
        resizedisplayorig = cv2.resize(displayorig, None, fx=0.2, fy=0.5, interpolation=cv2.INTER_LINEAR)
    else:
        resizedisplayorig = cv2.resize(displayorig, None, fx=0.5, fy=0.2, interpolation=cv2.INTER_LINEAR)
    resizedisplayorig = cv2.cvtColor(resizedisplayorig, cv2.COLOR_BGR2RGB)
    rdih, rdiw = resizedisplayorig.shape[:2]
    #cv2.imshow("Final Image", resizedisplayorig)
    self.importedImageFrame.setPixmap(QPixmap.fromImage(resizedisplayorig))     #Hangs here
    self.importedImageFrame.setAlignment(QtCore.Qt.AlignHCenter |      QtCore.Qt.AlignVCenter)
    self.inputImageLabel.setText(rdih + " X " + rdiw)

if __name__ == "__main__":
    app=QApplication(sys.argv)
    window=ezNPR()
    window.show()
    sys.exit(app.exec_())

2 个答案:

答案 0 :(得分:1)

是的,今天尝试我得到了一个很好的解决方案。 如果你喜欢它并工作,请点赞。谢谢

import React, {useState, useEffect} from "react";
import Moment from "react-moment";
import "moment-timezone";
import moment from "moment";

const Date = () =>{
  const [dateToFormat, setdateToFormat] = useState(moment().toDate().getTime())
  const updateTime = () => {
    let clock = moment().toDate().getTime()
  }
  setInterval(updateTime, 1000)

  useEffect(() => {
    let time = updateTime;
    setdateToFormat(
      time
    );
  },[]);
  
  return(
    <div>
        <Moment interval={1} unit="seconds">
              {dateToFormat}
        </Moment>
    </div>
  )
}


export default Date;

答案 1 :(得分:0)

官方React docs https://reactjs.org/docs/rendering-elements.html#updating-the-rendered-element

中有一个例子

但它的要点是你需要使用setInterval来更新组件的状态。这将导致组件在没有页面刷新的情况下重新渲染。

在您的情况下,您希望将date保存到状态的组件(例如在构造函数中),然后从渲染状态中读取它。然后使用setInterval每秒更新一次状态。

import './Home.css';
import React, { Component } from 'react';
import Moment from 'react-moment';

export default class Home extends Component {
    constructor() {
         this.state.date = new Date();
    }
    updateTime(){
        var date = this.state.date
        this.setState({date: date.setSeconds(date.getSeconds() + 1);
    }
    componentDidMount(){
        setInterval(this.updateTime, 1000);
    }
    render() {
        const together = "2017-05-14T06:30";


        return (
            <div>
                <p><Moment interval={1000} diff={together} unit="seconds">{this.state.date}</Moment> Seconds</p>
                 // etc.  Everywhere you had date becomes this.state.date
            </div>
        );
    }
}