2016-11-23 100 views
0

试图遵循一个简单的时钟/倒计时教程阵营:为什么我的状态不确定?

constructor(props) { 
    super(props); 
    this.state = { 
     secondsRemaining: 10 
    }; 
    } 

    componentDidMount(){ 
    let interval = setInterval(this.timer, 1000); 
    this.setState({ secondsRemaining: this.state.secondsRemaining }) 
    this.setState({ interval: interval }); 
    }; 

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

    timer(){ 
    this.setState({ secondsRemaining: this.state.secondsRemaining -1 }); 
    }; 

很明显什么都没有,但是当我运行它,我得到一个错误的定时器功能说cannot read property secondsRemaining of undefined

这可能是什么愚蠢的我已经错过了,但我看不出它

跟着这个问题的答案:setInterval in a React app

+0

'this.timer.bind(this)' –

回答

0

myfunction.bind()方法指定在被调用时方法内部将引用this。为了确保当你调用this.timer()时,你实际上引用了你的组件状态,而不是引用它的对象,你将不得不通过this.timer.bind(this)

+0

不错的一个。我会接受它,当我可以:) –

0

由于setInterval将调用this.timer,这将是窗口对象。 您可以使用封:在执行方法的时刻

componentDidMount(){ 
    let currentInstance = this; 
    let interval = setInterval(function(){ currentInstance.timer(); }, 1000); 
    ... 
}; 

componentDidMount它初始化属性状态下,保存到变量currentInstance。 然后我们将currentInstance的值关闭到setInterval的第一个参数中。

0

timer定义为Arrow Function

timer() => this.setState({ secondsRemaining: this.state.secondsRemaining -1 }) 

OR

.bind你的方法里面constructor

constructor(props) { 
    super(props); 
    this.state = { 
     secondsRemaining: 10 
    }; 
    this.timer = this.timer.bind(this); 
} 

我不建议this.timer.bind(this)render;因为这样做,.bind将在每个渲染上创建一个新函数。

0

由于您的边界上下文。你可以使用箭头函数或this.timer.bind(this)

相关问题