反应计时器组件,setState不起作用

时间:2018-02-14 22:35:33

标签: javascript reactjs

我有以下React组件:

import React from 'react';
import PropTypes from 'prop-types';
import Timer from '../Timer';
import moment from 'moment';
require('moment-countdown');

class PageThreeInfoSection extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      date: this.getDate(),
    };

    this.getDate = this.getDate.bind(this);
  }

  getDate() {
    return moment().countdown("2018-02-22").toString();
  }

   componentWillMount() {
     this.interval = setInterval(() => {
       this.setState({
         date: this.getDate(),
       });
     }, 1000);
   }

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

  render() {
    const { date, } = this.state;
    const { joinedFriendNumber, } = this.props;
    return (
      <div className="mt-4 mb-5 mt-sm-0 mb-sm-0">
        <h5 id="scroll-title" className="col-24 text-uppercase text-dark mt-4 mb-2 p-0 px-sm-3">
          {joinedFriendNumber} Friends Have Joined So Far
        </h5>
        <div className="col-24 text-light smallest mb-2">
          Your friends need to confirm their email to get your points
        </div>
        <div className='timer-container'>
          <Timer time={date} />
        </div>
      </div>
    );
  }
}

PageThreeInfoSection.propTypes = {
  joinedFriendNumber: PropTypes.number,
};

PageThreeInfoSection.defaultProps = {
  joinedFriendNumber: 0,
};

export default PageThreeInfoSection;

定时器组件:

import React from 'react';
import * as PropTypes from 'prop-types';

const Timer = ({ time, }) => (
  <span className='timer'>
    {time}
  </span>
);

Timer.propTypes = {
  time: PropTypes.string,
};

export default Timer;

我试图每秒用新的时间更新计时器组件。所以DOM实时更新。麻烦的是,this.setState()似乎没有真正更新状态并导致渲染功能更新。

我使用服务器端渲染,这意味着componentDidMount似乎根本不起作用,它甚至不会被触发。

0 个答案:

没有答案