I want to monitor hash change and then change the state and rerender the component. so I want to know where to monitor the hash change in component lifecycle
example:
#/detail/:id => #/detail
{info:[a:1,b:2]} => {info:[]}
.#/detail/:id and #/detail are the same components
If you want your component to have event listeners, you want to add those event listeners in componentDidMount, and remove the event listeners in componentWillUmount.
componentDidMount() {
window.addEventListener("hashchange", this.doSomething, false);
}
componentWillUnmount() {
window.removeEventListener("hashchange", this.doSomething, false);
}
Use HashRouter
in index.js and withRouter
to get path parameters and getDerivedStateFromProps
to handle the states based on the url's hash.
index.js
import ReactDOM from 'react-dom';
import { HashRouter } from "react-router-dom";
import App from './App';
ReactDOM.render(
<HashRouter>
<App />
</HashRouter>,
document.getElementById('root')
);
App.js
import { withRouter } from 'react-router-dom';
class App extends Component {
state = { productId: null };
static getDerivedStateFromProps(nextProps){
const { location: { pathname } } = nextProps; // pathname e.g.: '/detail/:8'
const productId = pathname.split(':')[1] || null; // ProductId: 8 OR null;
return { productId };
}
...
}
export default withRouter(App);
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