簡體   English   中英

React - TypeError:無法讀取未定義的屬性“setState”

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM