React JS - 实时时钟更新

新手上路,请多包涵

我有一个时钟功能,可以获取时间并显示小时、分钟和秒,我正在尝试实时更新屏幕上的数据,但由于某种原因,我的 setInterval 功能没有达到我的预期。

我认为 React 的 render 方法应该是实时渲染数据。我需要ajax吗?谁能提供一些建议?

 var CityRow = React.createClass({

  render: function() {

    var currentdate = new Date();

    function getTime() {
      // get local time based on the UTC offset
      this.hours = currentdate.getUTCHours() + parseInt(this.props.UTCOffset);

      // correct for number over 24, and negatives
      if( this.hours >= 24 ){ this.hours = this.hours - 24; }
      if( this.hours < 0   ){ this.hours = this.hours + 12; }

      // add leading zero, first convert hours to string
      this.hours = this.hours + "";
      if( this.hours.length == 1 ){ this.hours = "0" + this.hours; }

      // minutes are the same on every time zone
      this.minutes = currentdate.getUTCMinutes();

      // add leading zero, first convert hours to string
      this.minutes = this.minutes + "";
      if( this.minutes.length == 1 ){ this.minutes = "0" + this.minutes; }

      this.seconds = currentdate.getUTCSeconds();
    }

    window.setInterval(function () {
      getTime();
    }, 1000);

    return(
      <div className="city-row" ref="cityRow">
        <span className="city-time">{this.hours}:{this.minutes}:{this.seconds}</span>
        </div>
      </div>
    )
  }
});

原文由 amoeboar 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 720
2 个回答

您的代码似乎有几个问题。首先是渲染函数中的关闭 div,它会导致您的元素甚至无法渲染。

接下来,您可能想看看 state/props 和 React 通用生命周期方法,以更好地了解程序流程。 setInterval 应该放在 componentDidMount 中,这样它就不会在每次组件渲染和创建大量计时器时都被调用。将小时、分钟和秒作为状态也可能会有所帮助,这样当这些更改时您的组件会自动重新呈现。

我在下面修改了你的代码,并在 jsfiddle 上放了一个例子。它没有正确打印秒数(就像在您的 getTime 方法中一样),但希望它能让您更好地了解逻辑应该如何流动。

https://jsfiddle.net/rpg6t4uc/

 var CityRow = React.createClass({
  setTime: function(){

    var currentdate = new Date();
    var hours = currentdate.getUTCHours() + parseInt(this.props.UTCOffset);

      // correct for number over 24, and negatives
      if( hours >= 24 ){ hours -= 24; }
      if( hours < 0   ){ hours += 12; }

      // add leading zero, first convert hours to string
      hours = hours + "";
      if( hours.length == 1 ){ hours = "0" + hours; }

      // minutes are the same on every time zone
      var minutes = currentdate.getUTCMinutes();

      // add leading zero, first convert hours to string
      minutes = minutes + "";
      if( minutes.length == 1 ){ minutes = "0" + minutes; }

      seconds = currentdate.getUTCSeconds();
      console.log(hours, minutes, seconds)
      this.setState({
        hours: hours,
        minutes: minutes,
        seconds: seconds
      });
  },
  componentWillMount: function(){
    this.setTime();
  },
  componentDidMount: function(){
     window.setInterval(function () {
      this.setTime();
    }.bind(this), 1000);
  },
  render: function() {

    return(
      <div className="city-row" ref="cityRow">
        <span className="city-time">{this.state.hours}:{this.state.minutes}:{this.state.seconds}</span>
      </div>
    )
  }
});

原文由 noveyak 发布,翻译遵循 CC BY-SA 3.0 许可协议

官方的 React Docs 准确地描述了你需要什么(甚至解释了为什么你应该按照描述的那样去做):

–> React 文档:状态和生命周期

CodePen 上的示例

 class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

原文由 KevinH 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题