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;

在更新状态时出现以下错误,即单击按钮时。

TypeError: Cannot read property 'setState' of undefined updateTime
C:/Users/YV/YVSCodes/React-Van/hi-app/src/setState-event-binding-exampleComponent.js:21
18 | updateTime() 19 | { 20 | //updating the time by set state

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()
        };
    });
};