我有這樣一個組成部分特定的功能:reactjs打電話的時候,頁面刷新或關閉
import React, { PropTypes, Component } from 'react'
class MyView extends Component {
componentDidMount() {
window.addEventListener('onbeforeunload', this.saveState())
}
componentWillUnmount() {
window.removeEventListener('beforeunload', this.saveState())
}
saveState() {
alert("exiting")
}
render() {
return (
<div>
Something
</div>
)
}
}
export default MyView
這裏,當用戶刷新頁面我想打電話給一個特定的funtion,當通話結束後我想的頁面是刷新。用戶關閉頁面時相同。
在我上面的代碼中,我添加了一個事件監聽器onbeforeunload
並調用了saveState
函數。
但這裏我的componentDidMount
工作正常。 onbeforeunload
和saveState
當頁面被加載而不是頁面被刷新或退出時,函數被正常調用。
這裏有什麼問題,以及如何在某人退出或刷新頁面時響應特定功能或發出警報?
在上面的代碼
嘗試刪除窗口事件偵聽器,猜測componentWillUnmount使用'window.on('beforeunload')'下面 –