首页 > 解决方案 > TypeError: this.state.toLocaleTimeString 不是 React 中的函数

问题描述

这是显示时间的代码。

我设置statenew 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 | 

我不明白是什么问题。

我该如何解决?

标签: javascriptreactjsjsx

解决方案


您没有使用任何密钥来存储/更新导致此错误的状态,因为 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文档有一些关于状态管理和其他相关主题的有用信息,你绝对应该看看这些信息,以了解状态如何工作并相应地重新渲染 UI。


推荐阅读