【问题标题】:react-router-dom - TypeError: Cannot read properties of undefined (reading 'pathname')react-router-dom - TypeError:无法读取未定义的属性(读取“路径名”)
【发布时间】:2021-11-24 17:58:01
【问题描述】:

在使用 react-router-dom 5.3.0 时,我正在打开一个模式但没有更改路由,并且出现此错误。

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

非常感谢任何帮助:-)

【问题讨论】:

  • context.location 未定义
  • 嗨@BENARDPatrick,你能再扩展一点吗,我不确定我的代码如何处理这个问题。
  • 您看到第二个堆栈跟踪错误了吗?第 104 行 createPath(context.location) ?它调用函数createPath,在其中,第 47 行的位置是未定义的。所以context.location 是未定义的......在你的代码中,你可以等待context.location 有一个想要的价值......
  • 感谢@BENARDPatrick。所有这些错误都发生在我的 node_modules 中的一个包(我相信是 react-router-dom)中。所以我在想问题出在包上?
  • 不管怎样,我刚刚将 react-router-dom 再次升级到最新版本,我实际上无法复制问题,让我们看看问题现在是否消失了。

标签: reactjs react-router-dom antd


【解决方案1】:

当我尝试使用 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 2015-11-22
    相关资源
    最近更新 更多