React:更新组件

时间:2018-05-23 17:38:34

标签: reactjs setinterval

我不确定我在这里缺少什么。我是React和JS的新手。下面是一个文件的完整代码以及我有兴趣修复的文章。

我正在尝试使用setInterval每秒更新一次状态,以便时间在屏幕上重新呈现和更新。控制台注销“你好!”声明每一秒,但时间永远不会更新。我在这里缺少什么?

感谢您的帮助!

import React, { Component } from 'react';

import DateDay from '../Date/Date';
import Time from '../Time/Time';
import './timedate.css'



class TimeDate extends Component{
  state = {
    curDate: '',
    curTime: '',
  };


componentDidMount() {


  const optionsDate = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
  const optionsTime = { hour: '2-digit', minute: '2-digit' };
  const today = new Date();

  setInterval( () => {
    this.setState({curDate : today.toLocaleString("en-us", optionsDate)}),
    this.setState({curTime : today.toLocaleString("en-us", optionsTime).slice(0, -3)}) //slice removes the AM/PM
    console.log('Hello!')
  },1000)
}

render () {
  let { curDate } = this.state;
  let { curTime } = this.state;

  return (
    <div className="timedate">
       <DateDay 
          dateDay={curDate}
        />
        <Time 
          time={curTime}
        />
    </div>
         );
      }
}

export default TimeDate;

3 个答案:

答案 0 :(得分:2)

您总是使用相同的日期

componentDidMount() {


  const optionsDate = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
  const optionsTime = { hour: '2-digit', minute: '2-digit' };
  // const today = new Date(); captures current date for every next call.

  setInterval( () => {
    const today = new Date(); // move it here
    this.setState({curDate : today.toLocaleString("en-us", optionsDate)}),
    this.setState({curTime : today.toLocaleString("en-us", optionsTime).slice(0, -3)}) //slice removes the AM/PM
    console.log('Hello!')
  },1000)
}

此外,您确实希望在卸载组件时停止间隔。你可以这样做

componentDidMount() {
  ...
  this.intervalId = setInterval(...)
}

componentWillUnmount() {
  clearInterval(this.intervalId)
}

答案 1 :(得分:0)

您已以错误的方式初始化状态。状态初始化应该在构造函数中。

constructor() {
  super();
  this.state = {
    curDate: '',
    curTime: '',
  }
}

答案 2 :(得分:0)

您没有渲染秒数字段,因此每秒数据都不会更新,您还需要在setInterval中计算日期

class TimeDate extends React.Component {
      state = {
        curDate: "",
        curTime: ""
      };

      componentDidMount() {
        const optionsDate = {
          weekday: "long",
          year: "numeric",
          month: "long",
          day: "numeric"
        };
        const optionsTime = {
          hour: "2-digit",
          minute: "2-digit",
          second: "2-digit"
        };

        setInterval(() => {
          const today = new Date();
          this.setState({ curDate: today.toLocaleString("en-us", optionsDate) }),
            this.setState({ curTime: today.toLocaleString("en-us", optionsTime) }); //slice removes the AM/PM
          console.log("Hello!");
        }, 1000);
      }

    render () {
      let { curDate } = this.state;
      let { curTime } = this.state;

      return (
        <div className="timedate">
           <DateDay 
              dateDay={curDate}
            />
            <Time 
              time={curTime}
            />
        </div>
      );
    }
}

<强> Working DEMO