react 简单倒计时

倒计时组件react

import React, { Component } from 'react'

export default class countDown extends Component {
    constructor(props) {
        super(props)
        this.state = {
            second: this.props.value
        }
    }
    componentDidMount () {
        this.countDown()
    }
    componentWillUnmount () {
        if (this.timmerId) clearInterval(this.timmerId)
    }
    componentDidUpdate (preProps) {
        if (preProps.value !== this.props.value) {
            if (this.timmerId) clearInterval(this.timmerId)
            this.setState({
                second: this.props.value
            }, () => {
                this.countDown()
            })
        }
    }
    countDown = () => {
        this.timmerId = setInterval(() => {
            this.setState({
                second: this.state.second - 1
            }, () => {
                if (this.state.second <= 0) {
                    clearInterval(this.timmerId)
                }
            })
        }, 1000)
    }
    render() {
        return (
            <div>
                {this.state.second}
            </div>
        )
    }
}

须要手动更新时
1.手动更新key组件从新渲染this

<CountDown key={this.state.key} value={this.state.value}/>

2.应该能够使用ref,操做~~~code

相关文章
相关标签/搜索