在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ 執(zhí)行多個(gè)setTimeout事件,第一個(gè)會(huì)失效

執(zhí)行多個(gè)setTimeout事件,第一個(gè)會(huì)失效

//一個(gè)提示組件
class Notice extends React.Component {
    constructor(props) {
        super(props);
        this.onClick = this.onClick.bind(this);
        this.onRemove = this.onRemove.bind(this);
    }

//每渲染一個(gè)組件,3秒之后執(zhí)行onRemove刪掉。但連續(xù)渲染多個(gè)組件,第一個(gè)渲染的組件不會(huì)被刪掉。    
    componentDidMount(){
        const props = this.props;
        this.timer = setTimeout(()=>{
            this.props.onRemove(props.item.id)
        }, 3000);
    }

    componentWillUnmount(){
        clearTimeout(this.timer);
    }

    onClick(){
        const props = this.props;
        props.onClick(props.item.id);
    }

    onRemove(e){
        const props = this.props;
        e.stopPropagation();
        props.onRemove(props.item.id)
    }

    render(){
        const item = this.props.item;
        return 
            <div  onClick={()=>this.onClick()} >
                提示內(nèi)容
                <Icon onClick={this.onRemove}/>
            </div>
    }

}

我腦洞大開的加了(),似乎就解決失效的問題,但是會(huì)報(bào)錯(cuò) setTimeout(...) is not a function


componentDidMount(){
    const props = this.props;
    this.timer = setTimeout(()=>{
        this.props.onRemove(props.item.id)
    }, 3000)();
}
回答
編輯回答
未命名

setTimeout是存儲(chǔ)在data中的timer中的,所以在每次使用到定時(shí)器的時(shí)候應(yīng)該這么用:

clearTimeout(this.timer); //不管有沒有在運(yùn)行的定時(shí)器,先清除總沒錯(cuò)
this.timer = setTimeout(...); //再開一個(gè)定時(shí)器

希望能幫助到你!

2017年8月6日 10:33
編輯回答
久不遇

setTime不是方法,自調(diào)用當(dāng)然不行啦;
至于為啥刪不掉,由于不知道你的刪除方法是什么,我只能試驗(yàn)下setTimeout,發(fā)現(xiàn)每個(gè)組件都能運(yùn)行。所以我覺得可能是你的刪除方法的問題吧。

2017年7月12日 15:24