原生js
useEffect(() => {
const xxx = () => {
// todo
};
document.addEventListener('hashchange', xxx);
return () => {
document.removeEventListener('hashchange', xxx);
};
}, []);
使用react router history.listen
import {useHistory} from 'react-router-dom';
const history = useHistory();
useEffect(() => {
const unlisten = history.listen((route) => {
const {pathname} = route;
if (pathname === '/home/xxx') {
//todo
}
});
// 销毁
return unlisten;
}, []);