javascript - TypeError: this.state.toLocaleTimeString 不是 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 |
我不明白是什么问题。
我该如何解决?
解决方案
您没有使用任何密钥来存储/更新导致此错误的状态,因为 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。
推荐阅读
- apache - 使用 Tomcat 配置带有 HTTPS 反向代理的 Bitbucket 服务器的问题
- javascript - 聚合物`
`: 哪一行代码停止将同一自定义样式模板模块的多个导入附加到 DOM? - python - 如何从数组中删除字符并计算出现次数到 CSV 文件
- node.js - 在无服务器(nodejs 8)中调用 lambda 的正确方法
- angular - 角度中的类或函数实用程序
- python-2.7 - 从文件中读取行,在每行中添加 String + 换行符并写入目标文件
- c# - 来自 RefCount() 的 Observable 不会停止发布
- sql - 在联结表中,如果我需要一个单一的唯一标识符和一个单独的唯一复合标识符,哪个应该是主键?
- javascript - 使用反应原生拖动移动的 Animated.Image
- python-3.x - await 似乎阻止了 asycio.Future