![](/img/trans.png)
[英]React: TypeError: Cannot read property 'setState' of undefined
[英]React - TypeError: Cannot read property 'setState' of undefined
我无法弄清楚我的代码有什么问题。
import React from 'react'; import './App.css'; class Clock extends React.Component { constructor(props) { super(props); //defining state this.state={date:new Date()}; } updateTime() { //updating the time by set state this.setState( (state,props) => {date:new Date()} ); } render() { return ( <div> <h2>Now the time is {this.state.date.toLocaleTimeString()}</h2> <button onClick={this.updateTime}>Update Time</button> </div> ); } } export default Clock;
更新状态时出现以下错误,即单击按钮时。
类型错误:无法读取未定义更新时间的属性“setState”
C:/Users/YV/YVSCodes/React-Van/hi-app/src/setState-event-binding-exampleComponent.js:21
18 | 更新时间() 19 | { 20 | //通过设置状态更新时间21 | this.setState( (state,props) => {date:new Date()} );
你需要绑定 updateTime
constructor(props) {
...
this.updateTime = this.updateTime.bind(this)
}
或使用箭头功能
updateTime = () => {
//updating the time by set state
this.setState( (state,props) => {date:new Date()} );
}
并将您的 setState 更改为
this.setState({
date: new Date()
});
或者
this.setState( (state,props) => ({date:new Date()}) );
只需更换
updateTime() {
//updating the time by set state
this.setState( (state,props) => {date:new Date()} );
}
有了这个
updateTime = () => {
this.setState((state, props) => {
return {
date: new Date()
};
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.