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

IT技术 reactjs react-hooks
2021-04-08 02:15:50

useHistory 给出此错误:

无法编译 ./src/pages/UserForm/_UserForm.js 尝试导入错误:“useHistory”未从“react-router-dom”导出。此错误发生在构建期间,无法消除。

react-router-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
4个回答

react-router-dom v6 useHistory()中被useNavigate().

您可以使用:

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

我将 react-router-dom 的版本升级为

5.2.0

它现在正在工作。

UseHistory 已被 useNavigate 取代。所以试试这个👇👇

导入 { useNavigate } from 'react-router-dom';

const 导航 = useNavigate(); 导航('/家')

接受的答案已经说了完全相同的事情。
2021-06-10 02:15:50

如果你必须坚持使用最新的 react-router-dom v6.0.0,那么用 useNavigate 替换 useHistory。否则,将您的 react-router-dom 降级到 v5.2.0,您的代码就可以正常工作。