2017-06-15 113 views
0

我對於使用反應非常新,所以我嘗試創建一個小型定時器應用程序,但運行此代碼時收到以下錯誤:
(第40行:' timeDisplay」沒有定義沒有基金)未在React組件中定義'函數'

class Home extends React.Component { 
    constructor(props) { 
     super(props); 


     // Four states: 
     // work , workStop, break, breakStop 

     this.state = { 
      status: 'workStop', 
      time: 1500 
     } 
    } 

    componentDidMount() { 
     var interval = setInterval(this.timeTick, 1000); 
     this.setState({interval}); 
    } 

    componentWillUnmount() { 
     clearInterval(this.state.interval); 
    } 

    timeTick =() => { 
     if (this.state.time !== 0) 
      this.setState({ 
       time: this.state.time - 1 
      }); 
    } 

    timeDisplay =() => { 
     const minute = Math.floor(this.state.time/60); 
     const second = (this.state.time % 60) < 10 ? '0' + (this.state.time % 60) : (this.state.time % 60); 
     return (minute + ' : ' + second); 
    } 

    render() { 
     const time = timeDisplay(); 
     return (
      <div> 
       <p className='timer'>{time}</p> 
      </div> 
     ) 
    } 
} 

不知道該怎麼在這種情況下做的,我用箭頭功能定義的組件內部的timeDisplay方法。

+2

將以下行更改爲:const time = this.timeDisplay();. –

回答

3

那麼timeDisplay是Home組件實例的成員。您需要this才能訪問該功能。因此,使用:

const time = this.timeDisplay();

是正確的,而不是

const time = timeDisplay();

0

在類訪問實例方法總是使用this