useLocation投掷对象不是函数

时间:2020-08-15 08:25:07

标签: javascript reactjs react-router-dom

尝试使用react-router-dom 5.1中引入的useLocation钩子,但会引发错误-对象不是函数。

我在下面粘贴了我的代码要点

使用

反应-16.13

react-router-dom-5.2.0

App.js

<Router>
  <Switch>
    <Redirect exact from='/' to='/home' />
    <Route id='home' path='/home' component={Home} />

  </Switch>
</Router>

Home.js

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

function Home() {
  const [loc] = useLocation(); // throwing an error here
  console.log('ProductList -> loc', loc);
  
   return <div>Home</div>
}
Home.js:81 Uncaught TypeError: Object is not a function
    at PodList (Home.js:81)
    at renderWithHooks (react-dom.development.js:14803)
    at mountIndeterminateComponent (react-dom.development.js:17482)
    at beginWork (react-dom.development.js:18596)
    at HTMLUnknownElement.callCallback (react-dom.development.js:188)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:237)
    at invokeGuardedCallback (react-dom.development.js:292)
    at beginWork$1 (react-dom.development.js:23203)
    at performUnitOfWork (react-dom.development.js:22154)
    at workLoopSync (react-dom.development.js:22130)
    at performSyncWorkOnRoot (react-dom.development.js:21756)
    at scheduleUpdateOnFiber (react-dom.development.js:21188)
    at updateContainer (react-dom.development.js:24373)
    at react-dom.development.js:24758
    at unbatchedUpdates (react-dom.development.js:21903)
    at legacyRenderSubtreeIntoContainer (react-dom.development.js:24757)
    at Object.render (react-dom.development.js:24840)
    at Module../src/index.js (index.js:19)
    at __webpack_require__ (bootstrap:789)
    at fn (bootstrap:150)
    at Object.1 (utils.js:418)
    at __webpack_require__ (bootstrap:789)
    at checkDeferredModules (bootstrap:45)
    at Array.webpackJsonpCallback [as push] (bootstrap:32)
    at main.chunk.js:1

4 个答案:

答案 0 :(得分:2)

useLocation钩子不返回数组,而是代表当前URL的位置对象。您可以将其想像为useState,只要URL更改,它就会返回一个新位置。

更改代码:

const loc = useLocation();

答案 1 :(得分:1)

如果您查看the examples,就不会破坏useLocation的返回值。

更改:

const [loc] = useLocation();

收件人:

const loc = useLocation();
//    ^^^−−−−−−−−−−−−−−−−−−−−− no destructuring ([])

答案 2 :(得分:0)

用来自 react-router-dom 的 withRouter 包裹你的组件。以便您在 props 中收到 location 对象

这可能不是您查询的解决方案,但这将解决获取位置对象的用例。

答案 3 :(得分:0)

升级到最新版本的 react-router-dom,他们已经修复了。我在 5.0.0 版本中遇到了这个问题,然后我更新到 5.2.0 并得到了修复。