繁体   English   中英

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

[英]Attempted import error: 'useHistory' is not exported from 'react-router-dom'

useHistory 给出此错误:

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

反应路由器 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-router-dom v6中, useHistory()被替换为useNavigate()

您可以使用:

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

然后用useNavigate替换useHistory

const navigate = useNavigate();

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

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

想要在push/navigate中使用state do navigate('/path', { state: { name:'Xyz' }})

没有一个答案实际上提到如何复制以前可从 v5 useHistory挂钩但在 v6 中不再可用的方法,例如goBackgoForwardgo 以下示例取自迁移指南

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

这是使用来自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>
    </>
  );
}

在 v6 中, useHistoryuseNavigate取代。

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

  1. import { useNavigate } from 'react-router-dom'; 在文件的顶部。

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

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

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

5.2.0

它现在正在工作。

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

const navigate = useNavigate();

const confirm = (e) => {
    navigate.push('/')
}

只需将 useHistory 替换为 useNavigate 即可:

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

然后

const navigate = useNavigate();

最后的,

navigate("/home");

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

在 react-router-dom v6 中,useHistory() function 被 useNavigate() 替换。

常量导航 = useNavigate();

导航(“/登录”)

UseHistory 已替换为 useNavigate。 所以试试这个

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

常量导航 = useNavigate(); 导航('/家')

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

const anyName= useNavigate();

anyName("/home");

安装

npm i react-router-dom@5.0.0

因为 react-router-dom v6 useHistory() 被 useNavigate() 取代。

react-router-dom v5 useHistory ,但在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>;

对于那些使用 class 组件的人,请参考下面的链接

如何在 class 组件中使用 react-router-dom v6 导航

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

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

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

到 Go 返回使用navigate('../add',{replace:true})
到 Go 转发使用navigate('/add')

使用道具的历史

history.push('/home'); 

达到历史的例子:-

const functionalComponent = ({ history }) => { /* rest of the code here*/}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM