尝试导入错误:'useHistory'未从'react-router-dom'导出



useHistory给出此错误:

编译失败/src/pages/UserForm/UserForm.js尝试导入错误:"useHistory"未从"react router dom"导出。这在生成期间发生错误,无法消除。

react路由器dom版本:

4.3.1

代码:

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

react路由器中,dom v6useHistory()useNavigate()取代。

您可以使用:

import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
navigate('/home');

useHistory替换为useNavigate,然后替换为

const navigate = useNavigate();

然后用navigate('/path')代替history.push('/path')

navigate('/path', { replace: true })更改history.replace('/path')

想要在推送/导航执行navigate('/path', { state: { name:'Xyz' }})中使用state

没有一个答案真正提到如何复制过去可从v5useHistory挂钩获得但在v6中不再可用的方法,例如goBackgoForwardgo。以下示例摘自迁移指南:

React Router v5应用程序使用useHistory钩子中的方法:

// 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>
</>
);
}

以下是使用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在v6中被useNavigate替换

只需将useHistory名称替换为useNavigate,或者按照以下3个简单步骤操作即可。

  1. import { useNavigate } from 'react-router-dom' ;

  2. const navigate = useNavigate();在您的函数中定义。

  3. navigate("/path_name");重定向到您的路径。

我将react路由器dom的版本升级为

5.2.0

并且它现在正在工作。

V6已废弃useHistory钩子。现在使用useNavigate钩子
用法

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

假设您有一个函数名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})
}

返回使用navigate('../add',{replace:true})
前进请使用navigate('/add')

import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
const confirm = (e) => {
navigate.push('/')
}

只需将useHistory替换为useNavigate this way:

import { useNavigate } from "react-router-dom";

然后

const navigate = useNavigate();

最后,

navigate("/home");

基于以上答案,如果v5存在问题,我将增加一分

如果你坚持使用react-router-domv5,你必须升级到5.2.0,问题就会得到解决,因为它是在5.2.0中引入的


或者您可以升级到v6并使用useNavigate而不是useHistory

import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
navigate('/home');

在react路由器中,dom v6的useHistory((函数被useNavigate((取代。

constnavigation=useNavigate((

导航("/login"(

如果必须坚持使用最新的react router dom v6.0.0,则用useNavigate替换useHistory。否则,将react路由器dom降级到v.2.0,代码就会正常工作。

react router dom v5useHistory,但在v6中应使用useNavigate挂钩

用法:

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>;

新版本有useNavigate,您可以从"react router dom"导入

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

相关内容

  • 没有找到相关文章

最新更新