ckinmind/react-cnode

关于设置定时器定时去获取数据

ckinmind opened this issue · 1 comments

定时器参考代码(外边包一层容器组件)

import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import messagesActions from '../../actions/messageActions';

class Timer extends Component {

    /** setInterval返回一个整数,表示定时器的编号,以后可以用来取消这个定时器*/
    componentDidMount() {
        /** 已登录才发送获取消息数目请求*/
        if(this.props.isLogined){
            this.props.getMessageCount(); /* 一开始发起一次请求*/
            this.interval = setInterval(() =>  this.props.getMessageCount(), 30000);
        }
    }

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

    render() {
        return (
            <div className="timer" style={{display:'none'}}></div>
        );
    }
}

const mapStateToProps = state => ({
    isLogined: state.User.isLogined
});

const mapDispatchToProps = dispatch => ({
    getMessageCount: bindActionCreators(messagesActions.getMessageCount, dispatch)
});

export default connect(mapStateToProps, mapDispatchToProps)(Timer);