反应错误。 this.state.time.toLocaleTimeString不是一个函数

时间:2018-03-06 17:13:43

标签: javascript reactjs

我试图在关闭计时器后更改state.time,但我总是收到错误:TypeError this.state.time.toLocaleTimeString不是函数。有什么问题?也许有人都知道......

import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import './index.css';

class Demoss extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      time: new Date()
    };

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

  componentDidMount() {
    this.timerId = setInterval(() => this.setState({
      time: new Date()
    }), 1000);
  }

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

  handleClick() {
    clearInterval(this.timerId);
    this.setState((prevState) => {
      return {time: prevState.time + 12}
    });
  }

  render() {
    if (this.state.time.toString().match(/\d\d:\d\d:\d\d/g)) {
      return (
        <div>
          <p>{this.state.time.toLocaleTimeString()}</p>
          <p>{this.timerId}</p>
          <button onClick={this.handleClick}>clearTimer</button>
        </div>
      );
    } else {
      return (
        <div>
          <p>{this.state.time}</p>
          <p>{this.timerId}</p>
          <button onClick={this.handleClick}>clearTimer</button>
        </div>
      );      
    }

  }
}

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

1 个答案:

答案 0 :(得分:3)

这是因为您在日期中添加了12,从而将其转换为数字。您可以像这样增加日期:

Person.objects.annotate(num_readings=Count('books__reading')) \
            .order_by('-num_readings')

Fiddle