react-router-dom - TypeError: Cannot read properties of undefined (reading 'pathname')

react-router-dom - TypeError: Cannot read properties of undefined (reading 'pathname')

在使用react-router-dom 5.3.0时,我打开了一个模态,但没有改变路线,出现了这个错误。

我已经将 react-router-dom 降级到 5.2.0 并且没有出现这个错误。

非常感谢任何帮助:-)

当我尝试使用 location.pathname 访问当前 URL 时,我在升级 react-router-dom 版本后遇到了同样的错误。

使用 useLocation() 钩子解决了我的问题:

import { useLocation } from 'react-router-dom';

// getting current pathname with custom hook

const useName = () => {
const location = useLocation();
return location.pathname;
}