javascript - react 计时器如何实现定时任务来从数据库去数据并放在state中
高洛峰
高洛峰 2017-04-10 17:35:01
[JavaScript讨论组]

我现在有赢组件,是从数据库中取得数据,并通过state状态存放

callGetMvnDataPackageLogFn(orderCodeData).then((res) => {
      this.setState({ data: res.data });
    });

我现在想要给这个添加一个计时器去定时请求数据,我自己使用的是:

const intervals = stInterval(function(){
  callGetMvnDataPackageLogFn(orderCodeData).then((res) => {
    this.setState({ data: res.data });
  });
},200)

但是这并不行,请问该如何写?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(2)
PHP中文网

React官网首页的定时器例子,自己琢磨下!

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

  tick() {
    this.setState((prevState) => ({
      secondsElapsed: prevState.secondsElapsed + 1
    }));
  }

  componentDidMount() {
    this.interval = setInterval(() => this.tick(), 1000);
  }

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

  render() {
    return (
      <p>Seconds Elapsed: {this.state.secondsElapsed}</p>
    );
  }
}

ReactDOM.render(<Timer />, mountNode);
阿神

计时器要在componentDidMount生命周期方法挂上,然后在componentWillUnmount生命周期方法清除。

下面是ES6(Class)的语法范例:

  componentDidMount() {

    //this.timer = setInterval(this.tick.bind(this), 50); //或
    this.timer = setInterval(() => this.tick(), 50);
  }
  componentWillUnmount() {
     clearInterval(this.timer);
  }

  tick() {
    // 每50ms执行一次

    this.setState({
      elapsed: new Date() - this.props.start
    });

  }

这个范例是参考自: https://codepen.io/cmymikechu...

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号