[英]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.