【问题标题】:How to detect if react-router is set?如何检测是否设置了 react-router?
【发布时间】:2020-05-15 16:53:32
【问题描述】:

我在第三方组件中使用 react-router-dom hook useLocation()。

此组件行为默认取决于当前路由,但也可以在没有 react-router 的应用中使用(组件的用户不应该关心它)

问题是当组件在 react-router 范围之外使用时会抛出错误:

Cannot read property 'location' of undefined

我的问题是如何知道我是否可以使用 useLocation() 钩子(如何知道组件是否在 react-router 上下文中)?

【问题讨论】:

标签: reactjs react-router react-router-dom


【解决方案1】:

@Krzysztof Cieslinski 提出的类似问题的最简单解决方案是将 useLocation() 钩子包装在 try/catch 块中:

let path = ''
try {
  path = useLocation().pathname
} catch (e) {}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 2016-12-05
    • 1970-01-01
    • 1970-01-01
    • 2019-12-09
    • 1970-01-01
    相关资源
    最近更新 更多