React 应用程序中的 setInterval

新手上路,请多包涵

我在 React 上还是个新手,但我一直在慢慢地磨练,我遇到了一些我被困住的东西。

我正在尝试在 React 中构建一个“计时器”组件,老实说,我不知道我这样做是否正确(或有效)。在下面的代码中,我将状态设置为返回一个对象 { currentCount: 10 } ,并且一直在玩弄 componentDidMountcomponentWillUnmountrender ,我只能让状态从 10 到 9“倒计时”。

两部分问题:我做错了什么?而且,有没有更有效的方法来使用 setTimeout (而不是使用 componentDidMountcomponentWillUnmount )?

先感谢您。

import React from 'react';

var Clock = React.createClass({

  getInitialState: function() {
    return { currentCount: 10 };
  },

  componentDidMount: function() {
    this.countdown = setInterval(this.timer, 1000);
  },

  componentWillUnmount: function() {
    clearInterval(this.countdown);
  },

  timer: function() {
    this.setState({ currentCount: 10 });
  },

  render: function() {
    var displayCount = this.state.currentCount--;
    return (
      <section>
        {displayCount}
      </section>
    );
  }

});

module.exports = Clock;

原文由 Jose 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 601
2 个回答

我发现您的代码有 4 个问题:

  • 在您的计时器方法中,您始终将当前计数设置为 10

  • 您尝试在渲染方法中更新状态

  • 您不使用 setState 方法来实际更改状态

  • 您没有将您的 intervalId 存储在状态中

让我们尝试解决这个问题:

 componentDidMount: function() {
 var intervalId = setInterval(this.timer, 1000);
 // store intervalId in the state so it can be accessed later:
 this.setState({intervalId: intervalId});
 },

 componentWillUnmount: function() {
 // use intervalId from the state to clear the interval
 clearInterval(this.state.intervalId);
 },

 timer: function() {
 // setState method is used to update the state
 this.setState({ currentCount: this.state.currentCount -1 });
 },

 render: function() {
 // You do not need to decrease the value here
 return (
 <section>
 {this.state.currentCount}
 </section>
 );
 }

这将导致计时器从 10 减少到 -N。如果您希望计时器减少到 0,您可以使用稍作修改的版本:

 timer: function() {
 var newCount = this.state.currentCount - 1;
 if(newCount >= 0) {
 this.setState({ currentCount: newCount });
 } else {
 clearInterval(this.state.intervalId);
 }
 },

原文由 dotnetom 发布,翻译遵循 CC BY-SA 4.0 许可协议

使用 class Clock extends Component

 import React, { Component } from 'react';

class Clock extends Component {
  constructor(props){
    super(props);
    this.state = {currentCount: 10}
  }
  timer() {
    this.setState({
      currentCount: this.state.currentCount - 1
    })
    if(this.state.currentCount < 1) {
      clearInterval(this.intervalId);
    }
  }
  componentDidMount() {
    this.intervalId = setInterval(this.timer.bind(this), 1000);
  }
  componentWillUnmount(){
    clearInterval(this.intervalId);
  }
  render() {
    return(
      <div>{this.state.currentCount}</div>
    );
  }
}

module.exports = Clock;

原文由 Greg Herbowicz 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题