第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

React如何移除事件監(jiān)聽?

React如何移除事件監(jiān)聽?

炎炎設計 2019-03-25 11:28:58
問題描述1、在組件加載時,利用生命周期componentDidMount中添加事件監(jiān)聽。但在組件卸載時,在componentWillUnmount中無法移除事件2、而在Angular框架中,就是采用在組件卸載時移除事件就可以成功,而在React中此思路完全失效,為什么會有這種差異?React版本信息相關代碼class Product extends Component {     constructor() {        super();     }    // 組件加載時     componentDidMount() {        this.scrollEvent();     }    // 組件卸載時     componentWillUnmount() {         window.removeEventListener("scroll", this.onScroll.bind(this));     }    // 添加事件監(jiān)聽     scrollEvent() {         window.addEventListener("scroll", this.onScroll.bind(this));     }    // 事件監(jiān)聽方法     onScroll() {         console.log("滾動條正在滾動");     } }你期待的結果是什么?實際看到的錯誤信息又是什么?1、期望結果是:在組件完成卸載時,移除事件監(jiān)聽,onScroll方法停止執(zhí)行輸出"滾動條正在滾動"字符串2、實際結果是:當前組件已經(jīng)卸載,已經(jīng)進入到另一個組件時,onScroll方法仍然在執(zhí)行輸出"滾動條正在滾動"字符串
查看完整描述

2 回答

?
弒天下

TA貢獻1818條經(jīng)驗 獲得超8個贊

bind()會創(chuàng)建一個新的函數(shù),所以示例中添加和解除綁定的不是同一個函數(shù):

function a () {}
a === a  // truea.bind(this) === a.bind(this)  // false

在 constructor 中綁定 this:

class Product extends Component {
    constructor() {        super();        this.onScroll = this.onScroll.bind(this)
    }    // 組件加載時
    componentDidMount() {        this.scrollEvent();
    }    // 組件卸載時
    componentWillUnmount() {
        window.removeEventListener("scroll", this.onScroll);
    }    // 添加事件監(jiān)聽
    scrollEvent() {
        window.addEventListener("scroll", this.onScroll);
    }    // 事件監(jiān)聽方法
    onScroll() {
        console.log("滾動條正在滾動");
    }
}


查看完整回答
反對 回復 2019-03-25
  • 2 回答
  • 0 關注
  • 4534 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號