2017-07-18 71 views
1

我正在讀的官方教程反應網站。在有關生命週期方法的示例中,在componentDidMount方法下,將timerID設置爲setInterval函數。使用的setInterval在陣營組件

我的問題是,即使是的timerId初始化,這是從來沒有所謂的在整個應用程序,應用如何工作沒有顯式調用的timerId在應用程序中的任何地方。這是下面的代碼。

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

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

    componentWillUnmount() { 
    clearInterval(this.timerID); 
    } 

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

    render() { 
    return (
     <div> 
     <h1>Hello, world!</h1> 
     <h2>It is {this.state.date.toLocaleTimeString()}.</h2> 
     </div> 
    ); 
    } 
} 

ReactDOM.render(
    <Clock />, 
    document.getElementById('root') 

); 
+0

您的鏈接不工作。 –

+0

@KyleRichardson抱歉給我帶來了不便,現在我已經在代碼中加入了這個問題。 –

回答

1

this.timerID是數字的,非零值,它鑑別由所述呼叫創建setInterval()定時器;這個值可以傳遞給clearInterval來清除定時器。

所以調用componentDidMount的setInterval的像

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

當您要執行的功能tick()壓腳提升every 1 sec a組件已安裝。現在,當您導航到另一個分量和當前的組件有卸載,如果你不清除間隔調用tick()功能,它會繼續執行。

因此,在你定時器清零其是通過setInterval返回的數字值被存儲在this.timerID

componentWillUnmount() { 
    clearInterval(this.timerID); 
    } 

這樣的完整代碼作爲陣營文檔提供識別的componentWillUnmount功能是

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

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

    componentWillUnmount() { 
    clearInterval(this.timerID); 
    } 

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

    render() { 
    return (
     <div> 
     <h1>Hello, world!</h1> 
     <h2>It is {this.state.date.toLocaleTimeString()}.</h2> 
     </div> 
    ); 
    } 
} 

ReactDOM.render(
    <Clock />, 
    document.getElementById('root') 
); 
+0

非常感謝你,你一直很有幫助 –

1

很簡單。只要它陣營執行componentDidMount()生命週期的方法,所述計時器開始運行。

this.timerID = setInterval(
    () => this.tick(), 
     1000 
    ); 

上述計時器將運行,直到組件被卸載(根據您的代碼)。代碼以這種方式工作並不令人驚訝。