javascript - 在 componentWillUnmount 中停止计时器

标签 javascript reactjs ecmascript-6

我正在制作一个小倒数计时器作为 React 练习(为我自己,而不是类或其他任何东西)并且一切正常(尽管笔记总是受欢迎的)除了我注意到即使在组件完成后它也会继续倒计时卸载。

所以现在我想让它在卸载时停止,但似乎做不对。卸载时停止 setInterval 的协议(protocol)是什么?这是我拥有的:

class TimerVal extends Component {
  constructor(props) {
    super(props)
    this.state = {
      timeToGo: 30
    }
  }
  secondsToMMSS(seconds) {
    //returns "mm:ss"
  }
  componentDidMount() {
    setInterval(
      () => this.setState({
        timeToGo: this.state.timeToGo - 1
      }),
      1000
    )
  }
  componentWillUnmount() {
    () => this.setState({
      timeToGo: undefined
    })
  }
  render() {
    // styles
    console.log(this.state)
    const count = ( this.state.timeToGo > 0 ) ? this.secondsToMMSS(this.state.timeToGo) : "00:00"
    console.log(count)
    return(
      <div style={timerStyle}>
        <span style={timerSpanStyle}>
          {count}
        </span>
      </div>
    );
  }
}

最佳答案

一些事情。首先,这没有做任何事情:

() => this.setState({
  timeToGo: undefined
})

您只是定义了一个匿名函数,什么都不做。接下来,不要在倒计时停止时将 timeToGo 设置为 undefined。间隔将继续进行。相反,清除间隔:

this.interval = setInterval(
  () => this.setState({
    timeToGo: this.state.timeToGo - 1
  }),
  1000
)

然后在 componentWillUnmount 中:

clearInterval(this.interval)

这将彻底清除倒计时。最后,在倒计时到0的时候清除interval,否则会继续运行。这会消耗资源:

this.interval = setInterval(
  () => {
    if(this.state.timeToGo > 0) {
      this.setState(prevState => ({
        timeToGo: prevState.timeToGo - 1
      }))
    } else {
      clearInterval(this.interval)
    }
  },
  1000
)

一旦达到 0,这将清除间隔。另外,请注意我使用了 prevState。由于 setState 是异步的,这确保它正在访问正确的状态。

关于javascript - 在 componentWillUnmount 中停止计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46024944/

相关文章:

javascript - Bootstrap 根据在第一个下拉列表中点击的 li 显示/隐藏 li 元素

javascript - 在状态变化时使用react,useState 和 useEffect 是否也更新了?

javascript - 如何覆盖 react-router-dom Link 组件反向链接?

javascript - 使用map从数组的数组创建新数组的更好方法

javascript - 如何从子组件中的对象中获取数据并将其传递给React中父组件中的方法

javascript - js : format txt data to json data

javascript - enzyme wrapper.find(..).simulate keypress 不触发事件监听器

javascript - AngularJS: chop 在 ng-repeat/ng-bind-html 中绑定(bind)的多行 HTML

javascript - 在 JavaScript 数组中更新现有变量

javascript - 通过检查响应来处理 Promise 中的错误