倒计时组件

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组件重新渲染

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

2.应该可以使用ref,操作~~~


xpin
24 声望1 粉丝