I have a ponent like:
import React, { PropTypes, Component } from 'react'
class MyView extends Component {
ponentDidMount() {
window.addEventListener('onbeforeunload', this.saveState())
}
ponentWillUnmount() {
window.removeEventListener('beforeunload', this.saveState())
}
saveState() {
alert("exiting")
}
render() {
return (
<div>
Something
</div>
)
}
}
export default MyView
Here when a user refresh the page I want to call a specific funtion and when call is finished I want the page to be refreshed. Same when user closes the page.
In my above code I am adding an event listener onbeforeunload
and calling a saveState
function.
But here my ponentDidMount
is working normally. onbeforeunload
and saveState
function is called normally when page is loaded not when page is refreshed or exited.
What is wrong in here and how can I call specific funcitn or give alert when someone exits or refresh the page in react ?
In the above code
I have a ponent like:
import React, { PropTypes, Component } from 'react'
class MyView extends Component {
ponentDidMount() {
window.addEventListener('onbeforeunload', this.saveState())
}
ponentWillUnmount() {
window.removeEventListener('beforeunload', this.saveState())
}
saveState() {
alert("exiting")
}
render() {
return (
<div>
Something
</div>
)
}
}
export default MyView
Here when a user refresh the page I want to call a specific funtion and when call is finished I want the page to be refreshed. Same when user closes the page.
In my above code I am adding an event listener onbeforeunload
and calling a saveState
function.
But here my ponentDidMount
is working normally. onbeforeunload
and saveState
function is called normally when page is loaded not when page is refreshed or exited.
What is wrong in here and how can I call specific funcitn or give alert when someone exits or refresh the page in react ?
In the above code
Share Improve this question asked Aug 22, 2016 at 5:00 varadvarad 8,05922 gold badges67 silver badges114 bronze badges 1-
Try to remove window event listener, guess ponentWillUnmount uses
window.on('beforeunload')
underneath – Medet Tleukabiluly Commented Aug 22, 2016 at 5:25
2 Answers
Reset to default 1Attach beforeunload event on top level ponent and on beforeunload event make render empty which will trigger ponentWillUnmount of all child ponents.
import React, { PropTypes, Component } from 'react'
class App extends Component {
ponentDidMount() {
window.addEventListener('beforeunload', () =>{
this.setState({appended:true});
});
}
render() {
if(this.state.appended){
return false;
}else{
return (<MyView />)
}
}
}
class MyView extends Component {
ponentWillUnmount() {
this.saveState()
}
saveState() {
alert("exiting")
}
render() {
return (
<div>
Something
</div>
)
}
}
export default MyView
Hope this work for you.
According to this, try this syntax :
ponentDidMount() {
window.addEventListener('onbeforeunload', this.saveState)
}
ponentWillUnmount() {
window.removeEventListener('beforeunload', this.saveState)
}