2017-07-24 24 views
0

想法:我想在登錄後顯示時間並在註銷後隱藏它。程序工作,但註銷後,我得到警告(看圖3)。所以,我想知道:會警告影響應用程序,如果是的話,如何解決這個問題。

這裏的Clock.jsx:在卸載組件上調用setState()

import React from 'react' 

export class Clock extends React.Component { 
    constructor(props) { 
     super(props) 
     this.state = { 
      date: new Date() 
     } 
    } 

    componentDidMount() { 
     this.timerID = setInterval(
      () => this.tick(), 
      1000 
     ) 
    }  

    componentWillMount() { 
     clearInterval(this.timerID) 
    } 

    tick() { 
     this.setState({ 
      date: new Date() 
     }) 
    } 

    render() { 
     return (
      <div> 
       <hr /> 
       <p>Current Time: </p> 
       <p>{this.state.date.toLocaleTimeString()}.</p> 
       <hr /> 
      </div> 
     ) 
    } 
} 

撥打index.jsx該組件:

function Logout(props) { 
    return (  
     <div> 
      <button className="btn btn-danger" onClick={props.onClick}> 
       Logout 
      </button> 
      <Clock /> 
     </div> 
    ) 
} 

圖片1 - 登錄:

image 1

圖片2 - 登錄後:

image 2

圖片3 - 註銷後警告:

image 3

+1

當您單擊註銷,它卸載你的''成分? –

回答

0

嘗試調用clearInterval在componentWillUnmount。這可確保在時鐘組件在DOM中不可用時,不會調用寫在tick內的setState方法。

+1

您能否詳細說明一下,爲什麼在componentWillMount中調用clearInterval。 –

0

在Clock.jsx我輸入componentWillMount()而不是componentWillUnmount()時輸入錯誤。

舊的代碼片段:

componentWillMount() { 
    clearInterval(this.timerID) 
} 

修正:

componentWillUnmount() { 
    clearInterval(this.timerID) 
} 
相關問題