gpt4 book ai didi

javascript - React : implementing timer, 状态属性在 setState 中未定义,而方法在构造函数上绑定(bind)

转载 作者:行者123 更新时间:2023-12-01 01:46:45 24 4
gpt4 key购买 nike

我正在尝试在 React 中实现一个简单的计时器组件,该组件在 props 更新时开始运行。除了计时器之外,一切正常。• Prop 正在正确接收和处理。• 状态的初始“秒”属性在构造函数中定义。

但是 this.state 在从 componentDidMount 使用异步方法 setInterval 调用以运行计时器的 this.setState 中未定义。

我还尝试在构造函数中将 startTimer 方法绑定(bind)到 this ,但它抛出了相同的错误。 this.startTimer = this.startTimer.bind(this);

这是组件并提前致谢:

import React, { Component } from 'react';
import { connect } from "react-redux";

class Timer extends Component {
constructor(props) {
super(props);
this.state = { seconds: 0 }
this.intervalHandle;
}

//Component receives this.props.started === true properly
componentDidMount() {
if (this.props.started) {
this.startTimer();
}
}
//startTimer triggers correctly logging "STARTING"
startTimer() {
console.log("STARTING")
this.intervalHandle = setInterval(
this.tick, 1000);
}
//tick also triggers correctly logging "Ticking" every 1000ms
tick() {
console.log("TICKING")
//HERE IS THE ERROR: Uncaught TypeError: Cannot read property
//'seconds' of undefined, the console throws it once a seconds
this.setState({ seconds: this.state.seconds + 1 })
}
componentWillUnmount() {
if (!this.props.started) {
clearInterval(this.intervalHandle);
}
}
// Component initialy renders
render() {
return <span>:0{this.state.seconds}</span>
}
}
function mapStateToProps(state) {
return {
started: state.isStarted
}
}
export default connect(mapStateToProps)(Timer);

最佳答案

它未定义的原因是 this.tick 是一个函数,而您没有绑定(bind)它。

更改为

 this.intervalHandle = setInterval(this.tick.bind(this), 1000);

或者在构造函数中绑定(bind)它

 constructor(props){
super(props);
this.tick = this.tick.bind(this);
}

this.intervalHandle = setInterval(this.tick, 1000);

或使用箭头功能

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

tick = () => {
console.log("TICKING")
this.setState({ seconds: this.state.seconds + 1 })
}

这两项更改应该可以解决您的问题

关于javascript - React : implementing timer, 状态属性在 setState 中未定义,而方法在构造函数上绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51886911/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com