[英]Attempted import error: 'useHistory' is not exported from 'react-router-dom'
useHistory giving this error: useHistory 给出此错误:
Failed to compile./src/pages/UserForm/_UserForm.js Attempted import error: 'useHistory' is not exported from 'react-router-dom'.
编译失败。/src/pages/UserForm/_UserForm.js 尝试导入错误:“useHistory”未从“react-router-dom”导出。 This error occurred during the build time and cannot be dismissed.
此错误发生在构建期间,无法消除。
react-router-dom version:反应路由器 dom 版本:
4.3.1
4.3.1
Code:代码:
import React, { useState, Fragment } from 'react';
import FormUserDetails from './FormUserDetails';
import FormPersonalDetails from './FormPersonalDetails';
import Confirm from './Confirm';
import Success from './Success';
import Button from '@material-ui/core/Button';
import { Grid, makeStyles } from '@material-ui/core';
import { useHistory } from 'react-router-dom';
function UserForm() {
const [step, setStep] = useState(1);
const history = useHistory();
const StepButtons = (props) => (
<React.Fragment>
<Grid item xs={4}>
{props.value !== 'initial' ?
<Button variant="outlined" className={classes.button} onClick={(e) => previousStep(e)}>Back</Button> :
<Button variant="outlined" className={classes.button} onClick={(e) => reGenerate(e)}>Re-generate</Button>
}
</Grid>
<Grid item xs={4} />
<Grid item xs={4}>
{
props.value === 'confirm' ?
<Button variant="outlined" className={classes.button} style={{ float: "right" }} onClick={(e) => confirm(e)}>Confirm</Button> :
props.value !== 'final' ?
<Button variant="outlined" className={classes.button} style={{ float: "right" }} onClick={(e) => nextStep(e)}>Continue</Button> :
null
}
</Grid>
</React.Fragment>
);
const nextStep = (e) => {
e.preventDefault();
setStep(prevState => prevState + 1)
}
const previousStep = (e) => {
e.preventDefault();
setStep(prevState => prevState - 1)
}
const reGenerate = (e) => {
e.preventDefault();
}
const confirm = (e) => {
history.push('/')
}
return (
<div>
<h1>Hello</h1>
</div>
)
}
export default UserForm
In react-router-dom v6 useHistory()
is replaced by useNavigate()
.在react-router-dom v6中,
useHistory()
被替换为useNavigate()
。
You can use:您可以使用:
import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
navigate('/home');
Replace useHistory with useNavigate then然后用useNavigate替换useHistory
const navigate = useNavigate();
and then replace history.push('/path')
with navigate('/path')
然后用
navigate('/path')
替换history.push('/path')
path')
Change history.replace('/path')
with navigate('/path', { replace: true })
将
history.replace('/path')
更改为navigate('/path', { replace: true })
Want to use state
in push/navigate do navigate('/path', { state: { name:'Xyz' }})
想要在push/navigate中使用
state
do navigate('/path', { state: { name:'Xyz' }})
None of the answers actually mention how to replicate the methods which used to be available from the v5 useHistory
hook but which are no longer available in v6 eg goBack
, goForward
, go
.没有一个答案实际上提到如何复制以前可从 v5
useHistory
挂钩但在 v6 中不再可用的方法,例如goBack
、 goForward
、 go
。 The following example is taken from the migration guide :以下示例取自迁移指南:
useHistory
hook:useHistory
钩子中的方法 React Router v5 应用程序:// This is a React Router v5 app
import { useHistory } from "react-router-dom";
function App() {
const { go, goBack, goForward } = useHistory();
return (
<>
<button onClick={() => go(-2)}>
Go 2 pages back
</button>
<button onClick={goBack}>Go back</button>
<button onClick={goForward}>Go forward</button>
<button onClick={() => go(2)}>
Go 2 pages forward
</button>
</>
);
}
navigate
method from useNavigate
hook:useNavigate
挂钩的navigate
方法的 v6 等效应用程序:// This is a React Router v6 app
import { useNavigate } from "react-router-dom";
function App() {
const navigate = useNavigate();
return (
<>
<button onClick={() => navigate(-2)}>
Go 2 pages back
</button>
<button onClick={() => navigate(-1)}>Go back</button>
<button onClick={() => navigate(1)}>
Go forward
</button>
<button onClick={() => navigate(2)}>
Go 2 pages forward
</button>
</>
);
}
useHistory
is replace by useNavigate
in v6.useHistory
被useNavigate
取代。 Just replace useHistory name to useNavigate, or follow these 3 simple steps.只需将 useHistory 名称替换为 useNavigate,或按照以下 3 个简单步骤操作。
import { useNavigate } from 'react-router-dom';
on the top of your file.在文件的顶部。
const navigate = useNavigate();
define in your function.在您的 function 中定义。
navigate("/path_name");
redirect to your path.重定向到您的路径。
I upgraded the version of react-router-dom to我将 react-router-dom 的版本升级为
5.2.0
5.2.0
and it is working now.它现在正在工作。
import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
const confirm = (e) => {
navigate.push('/')
}
Just replace useHistory with useNavigate this way:只需将 useHistory 替换为 useNavigate 即可:
import { useNavigate } from "react-router-dom";
Then然后
const navigate = useNavigate();
Last,最后的,
navigate("/home");
If you must stick to the latest react-router-dom v6.0.0, then replace useHistory with useNavigate.如果你必须坚持使用最新的 react-router-dom v6.0.0,那么将 useHistory 替换为 useNavigate。 Else, downgrade your react-router-dom to v5.2.0 and your code works as it should.
否则,将您的 react-router-dom 降级到 v5.2.0 并且您的代码可以正常工作。
In react-router-dom v6 useHistory() function is replaced by useNavigate().在 react-router-dom v6 中,useHistory() function 被 useNavigate() 替换。
const navigate = useNavigate();常量导航 = useNavigate();
navigate("/login")导航(“/登录”)
UseHistory have been replaced with useNavigate. UseHistory 已替换为 useNavigate。 So try this
所以试试这个
import { useNavigate } from 'react-router-dom';从 'react-router-dom' 导入 { useNavigate };
const navigate = useNavigate();常量导航 = useNavigate(); navigate('/home')
导航('/家')
import { useNavigate } from "react-router-dom";
const anyName= useNavigate();
anyName("/home");
install安装
npm i react-router-dom@5.0.0
Because react-router-dom v6 useHistory() is replaced by useNavigate().因为 react-router-dom v6 useHistory() 被 useNavigate() 取代。
react-router-dom v5 useHistory
, but in v6
you should use useNavigate
hook react-router-dom v5
useHistory
,但在v6
中你应该使用useNavigate
钩子
Usage:用法:
import { useNavigate } from "react-router-dom";
function SignupForm() {
let navigate = useNavigate();
async function handleSubmit(event) {
event.preventDefault();
await submitForm(event.target);
navigate("../success", { replace: true });
}
return <form onSubmit={handleSubmit}>{/* ... */}</form>;
For those who use the class component please reference below link对于那些使用 class 组件的人,请参考下面的链接
How to use react-router-dom v6 navigate in class component 如何在 class 组件中使用 react-router-dom v6 导航
V6 has scrapped useHistory hook. V6废弃了 useHistory钩子。 now useNavigate hook is used.
现在使用useNavigate挂钩。
Usage用法
import {useNavigate} from 'react-router-dom';
let say you have a function name sendData假设您有一个 function 名称 sendData
function sendData(){
let data = {name,email,password}
let results = await fetch('http://localhost:8000/api/register',{
method:'POST',
headers:{
'Content-Type': 'application/json',
'Accept':'application/json'
},
body:JSON.stringify(data)
});
results = await results.json();
console.warn("results",results);
localStorage.setItem('user',JSON.stringify(results))
navigate('../add',{replace:true})
}
To Go Back use navigate('../add',{replace:true})
到 Go 返回使用
navigate('../add',{replace:true})
To Go Forward use navigate('/add')
到 Go 转发使用
navigate('/add')
Use history from props使用道具的历史
history.push('/home');
example of reaching history:-达到历史的例子:-
const functionalComponent = ({ history }) => { /* rest of the code here*/}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.