2017-07-24 23 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) 
} 
相关问题