简体   繁体   English

React-router - 挂钩 useHistory 错误:无法读取未定义的属性“历史”

[英]React-router - Hook useHistory Error: Cannot read property 'history' of undefined

I'm trying to use the hook useHistory fromdocumentation of react-router-dom .我正在尝试使用react-router-dom文档中的钩子 useHistory 。

I keep getting this error: TypeError: Cannot read property 'history' of undefined我不断收到此错误:TypeError:无法读取未定义的属性“历史”

Here an example: https://codesandbox.io/s/twilight-meadow-bwnt8?fontsize=14&hidenavigation=1&theme=dark这里有一个例子: https : //codesandbox.io/s/twilight-meadow-bwnt8?fontsize=14&hidenavigation=1&theme=dark

import React from 'react';
import { useHistory } from "react-router-dom";


function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

function App() {
  return (
     <HomeButton />
  );
}

export default App;

The useHistory hook only works inside of a Route. useHistory钩子仅在 Route 内工作。

It is the route that passes the history object to the useHistory hook.它是将历史对象传递给useHistory钩子的useHistory Which is why in this case it is undefined - there is no route to pass the history object to it.这就是为什么在这种情况下它是未定义的 - 没有将历史对象传递给它的路径。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法读取未定义的属性“历史”(React Router 5 的 useHistory 挂钩) - Cannot read property 'history' of undefined (useHistory hook of React Router 5) 设置 useHistory 挂钩时无法读取未定义的属性“历史记录” - Cannot read property 'history' of undefined when setting up a useHistory hook React-Router 错误“无法读取未定义的属性‘位置’” - React-Router Error "Cannot read property 'location' of undefined" 错误:无效的挂钩调用 - 在 react-router useHistory 中 - Error: Invalid hook call - in react-router useHistory 无法读取未定义的属性“历史记录”-react-router v4和create-react-app - Cannot read property 'history' of undefined — react-router v4 & create-react-app React Router - 无法读取未定义的属性“历史” - React Router - Cannot read property 'history' of undefined &#39;TypeError: 使用&#39;react-router-dom&#39; 的&#39;useHistory&#39; 钩子时无法读取未定义的属性(读取&#39;push&#39;)&#39; - 'TypeError: Cannot read properties of undefined (reading 'push')' when using 'useHistory' hook of 'react-router-dom' React-router - 无法读取undefined的属性&#39;query&#39; - React-router - Cannot read property 'query' of undefined React-router导致无法读取未定义的属性&#39;listen&#39; - React-router causes Cannot read property 'listen' of undefined react-router:无法读取undefined的属性&#39;push&#39; - react-router: Cannot read property 'push' of undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM