I need to save the url in local storage, whenever the component is unmounting:
componentWillUnmount(){
console.log("componentWillUnmount will call here.");
console.log("window.redirect.url",window.location.pathname);
localStorage.setItem("prevUrl",window.location.pathname);
}
In another case, where there is a case when an anchor tag is clicked, the above method is not called:
<a href="/differentpage">differentpage </a>
I am unable to execute the unmount method. Is there any way we can execute unmount?
Redirect to a different page out of the SPA context will lead you to step out from the react life cycle. it's like expecting to go through this cycle when clicking the refresh button.
What you can do though, is set a handler to this anchor tag with e.preventDefault()
to stop the default behavior and then do your stuff with the state and only when you are done, redirect the window path to the link provided via e.target.href
in this case.
Keep in mind though, you will lose any state updates after you redirect the window location to a different page outside your SPA.
Code Example:
const styles = {
fontFamily: 'sans-serif',
textAlign: 'center',
};
class App extends React.Component {
onClick = e => {
e.preventDefault();
// do whatever you want with the state, but keep inmind you will lose all the data once you redirect the window out of this context (consider persistent state with local storage?)
window.location = e.target.href;
}
render(){
return(
<div style={styles}>
<a href="https://google.com" onClick={this.onClick}>click!</a>
<h2>Redirect me! {'\u2728'}</h2>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
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