I need to redirect to main page when user refreshes other pages. It' s my attempt to add event listener for page refresh. But it doesn't work and I have Router.js?cf42:125 Uncaught RangeError: Maximum call stack size exceeded
in browser. Could you advise me how to cope with this error?
import {browserHistory} from 'react-router';
class MyComponent extends React.Component {
constructor(props, context) {
super(props, context);
this.onUnload = this.onUnload.bind(this);
}
componentDidMount() {
window.addEventListener('beforeunload', this.onUnload);
}
componentWillUnmount() {
window.removeEventListener('beforeunload', this.onUnload);
}
onUnload() {
browserHistory.push('/');
}
render() {
...
}
}
UPD: I have fixed RangeError. Now MyComponent
's page is redirected to main page but after that it opens again. I think that this happens because redirect doesn't stop page refresh.
If set to true, the browser will do a complete page refresh from the server and not from the cached version of the page. import React from 'react'; function App() { function refreshPage() { window. location. reload(false); } return ( <div> <button onClick={refreshPage}>Click to reload!
Using LocalStorage — Class Components Now let's say if we want to keep this count value persist when the page reloads, we can do that by simply introducing localStorage. As you can see, now we store the state value whenever we call the setState method. This is a simple approach to achieve what we want.
To redirect to another page on button click in React: Use the useNavigate() hook, e.g. const navigate = useNavigate(); . Call the navigate() function, passing it the path - navigate('/about') . The navigate() function lets us navigate programmatically.
Try window.location.href
instead of browserHistory.push
. This will help.
onUnload() {
window.location.href = "/";
}
Here is an example:
https://stackblitz.com/edit/react-rbfoic?file=src/App.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With