TypeError: this.state.toLocaleTimeString is not a function in React

TypeError: this.state.toLocaleTimeString is not a function in React

这是显示时间的代码。

我将 state 设置为 new Date() 并将 setState() new Date() 作为参数.

class Clock extends Component {
  constructor(props) {
    super(props)
    this.state = new Date()

  }

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

  componentWillUnmount() {
    clearInterval(this.timerID)
  }

  tick() {
    this.setState(new Date())
  }

  render() {
    return (
      <div>
        <h2>It is {this.state.toLocaleTimeString()}.</h2>
      </div>
    )
    
  }
}

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

运行 代码,出现如下错误

TypeError: this.state.toLocaleTimeString 不是函数

Clock.render
  29 | return (
  30 |   <div>
  31 |     <h1>Hello, world!</h1>
> 32 |     <h2>It is {this.state.toLocaleTimeString()}.</h2>
     | ^  33 |   </div>
  34 | )
  35 | 

我不明白是什么问题。

我该如何解决?

您没有使用 store/update 状态的任何键,这是导致此错误的原因,因为 React 找不到任何要更新的内容。我使用密钥 date 每秒存储和更新状态。

因此,状态将是

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

和报价函数更新。

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

还有渲染部分使用状态键。

<h2>It is {this.state.date.toLocaleTimeString()}.</h2>

您更新后的代码应该如下所示。

import { render } from "react-dom";
import React from "react";

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() {
    console.log(this.state);
    return (
      <div>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
render(<Clock />, rootElement);

React docs 有一些关于状态管理和其他相关主题的有用信息,您一定要看一看,以了解状态如何工作并相应地重新渲染 UI。

尝试在您的州声明中使用 this.state = {date: new Date()};