前端 React 如何做路由监听

277 阅读1分钟

原生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;
}, []);