反应-TypeError:无法读取未定义的属性“ setState”

时间:2020-03-30 04:25:32

标签: javascript reactjs dom-events setstate

我不知道自己的代码出了什么问题。

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:无法读取未定义的updateTime属性'setState'
C:/用户/YV/YVSCodes/React-Van/hi-app/src/setState-event-binding-exampleComponent.js:21
18 | updateTime()19 | {20 | //更新时间 按设置状态

21 | this.setState((state,props)=> {date:new Date()});

2 个答案:

答案 0 :(得分:0)

您需要绑定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()})  );

答案 1 :(得分:0)

直接替换

updateTime() {
    //updating the time by set state
    this.setState( (state,props) =>  {date:new Date()}  );
}

有了这个

updateTime = () => {
    this.setState((state, props) => {
        return {
          date: new Date()
        };
    });
};