![](/img/trans.png)
[英]Attempted import error: 'Outlet' is not exported from 'react-router-dom
[英]import error: 'useHistory' is not exported from 'react-router-dom'
我正在嘗試從“react-router-dom”導入 useHistory,但是,我收到此錯誤:導入錯誤:“useHistory”未從“react-router-dom”導出。
我也檢查了其他答案,例如嘗試導入錯誤:'useHistory' is not export from 'react-router-dom' this 但無濟於事。 我的 package.json 看起來像這樣
我正在使用 useHistory ,
import React from 'react';
import { useState, useEffect } from 'react';
import { useHistory } from 'react-router-dom';
export default function Login(){
const history = useHistory();
console.log(history)
}
但是,這條線工作正常,不會導致從 react-router-dom 導入問題。
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom'
有誰知道如何解決這個問題? 非常感激。
UseHistory 已經被替換為 useNavigate 所以試試這個👇👇
import { useNavigate } from 'react-router-dom';
在你的函數內部:
const navigate = useNavigate();
navigate('/home')
我希望這有效👌
如果您安裝 v6 或更高版本 react-router-dom,請useNavigate
react-router-dom": ^6.2.1
import { useNavigate } from "react-router-dom";
let navigate = useNavigate();
const onSubmit = async (e) => {
e.preventDefault();
await axios.post("http://localhost:3001/users", user);
navigate(`/`);
};
這不是庫的問題,而是 Typescript 類型的問題
嘗試為react-router-dom
重新安裝類型
npm install -save-dev @types/react-router-dom
對您的問題的正確答案是您需要確認您對歷史鈎子的使用在 BrowserRouter 的范圍內 - 快速解決方法是將 BrowserRouter 組件上移到 app.js 或 index.js - 只要當您在已經位於 BrowserRouter 上下文中的組件范圍內調用 useHistory 掛鈎時,您在 v5 中應該沒有問題。 評論 v6 的人仍然需要做同樣的修復,答案是不升級,盡管如果你有能力升級,我會這樣做。
建議修復:在 index.js 上渲染 BrowserRouter
// index.js
...
import { BrowserRouter } from 'react-router-dom' // <=V5 not compatible with V6
render(<BrowserRouter><App /></BrowserRouter>, document.getElementById('root'));
...
然后在組件內加載的任何組件上,您可以使用useHistory
了解有關歷史的更多信息以及可以加載的位置 - https://github.com/remix-run/history
// `useHistory` has been replaced by `useNavigate` in react-router-dom v6
import { useNavigate } from "react-router-dom";
function Invoices() {
let navigate = useNavigate();
return
(enter code here
<div>
<NewInvoiceForm
onSubmit={async event => {
let newInvoice = await createInvoice(
event.target
);
navigate(`/invoices/${newInvoice.id}`);
}}
/>
</div>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.