一跟着网上做react项目时,代码中以下代码:
import { HashRouter, Route, Switch, Redirect } from 'react-router-dom'
出现了以下俩个报错:
export 'Switch' (imported as 'Switch') was not found in 'react-router-dom'
export 'Redirect' (imported as 'Redirect') was not found in 'react-router-dom'
export 'withRouter' (imported as 'withRouter') was not found in 'react-router-dom'
原因:这些报错原因均为'Switch' 和'Redirect' 是react-router 5版本的接口,而最新版本是
"react-router-dom": "^6.2.1",并且已经将Switch改为Routes。
解决办法有二:
1.将所有 Switch 改为 Routes,Redirect 改为 Navigate ,withRouter改为 useNavigate
(vscode中,按快捷键:CTRL+F及可查找替换)
2.卸载新版本,再安装5的版本
npm uninstall react-router-dom
npm install react-router-dom@5