在 react-router-dom 中找不到导出 ‘useHistory’
Export ‘useHistory’ was not found in react-router-dom
要解决错误“在‘react-router-dom’中找不到导出‘useHistory’(导入为‘useHistory’)”,请改用useNavigate
钩子,例如
const navigate = useNavigate()
。该挂钩返回一个函数,允许您以编程方式导航。
// 👇️ import useNavigate import {useNavigate} from 'react-router-dom'; export default function App() { const navigate = useNavigate(); const handleClick = () => { // 👇️ navigate programmatically navigate('/about'); }; return ( <div> <button onClick={handleClick}>Navigate to About</button> </div> ); }
在 React Router 版本 6 中,useHistory()
钩子被替换为
useNavigate()
.
useNavigate
编程方式导航,例如在提交表单之后。我们传递给函数的参数与组件上的 propnavigate
相同。to
<Link to="/about">
如果要使用该history.replace()
方法
的等效项,请将options
参数传递给该navigate
函数。
import {useNavigate} from 'react-router-dom'; export default function App() { const navigate = useNavigate(); const handleClick = () => { // 👇️ replace set to true navigate('/about', {replace: true}); }; return ( <div> <button onClick={handleClick}>Navigate to About</button> </div> ); }
当replace
属性设置为true
选项对象上时,历史记录堆栈中的当前条目将被新的条目替换为新的。
这很有用,例如,当用户登录时 – 您不希望他们能够单击后退按钮并返回到登录页面。
Or if you have a route that redirects uses to a different page – you don’t want
users to click the back button and get redirected again.
You can also call the navigate
function with a delta to go back in the history
stack, e.g. navigate(-1)
is the same as hitting the back button.
Conclusion #
To solve the error “export ‘useHistory’ (imported as ‘useHistory’) was not
found in ‘react-router-dom'”, use the useNavigate
hook instead, e.g.
const navigate = useNavigate()
. The hook returns a function that lets you
navigate programmatically.