React导入react-router的withRouter报错及npm安装依赖警告如何解决?
React注册页面开发异常问题解决方案
问题1:Attempted import error: 'withRouter' is not exported from 'react-router' 报错
诱因
你当前安装的是react-router v6及以上版本,该版本已经正式移除了withRouter高阶组件API,因此无法从react-router包中导出该方法,触发导入报错。另外Web端React项目通常使用react-router-dom即可,不需要单独安装react-router依赖,也可能是包引用错误导致的问题。
修复方案
优先推荐适配v6版本的Hooks写法,无需降级版本:
- 替换导入的API,将
import { withRouter } from "react-router"改为import { useNavigate } from "react-router-dom" - 组件内用
useNavigate替代原有的history对象,删除导出时的withRouter包裹,修改后的完整代码如下:
import React, { useCallback } from "react"; import { useNavigate } from "react-router-dom"; import app from "../Firebase/firebase"; const Register = () => { const navigate = useNavigate(); const handleSignup = useCallback(async event => { event.preventDefault() const { email, password } = event.target.elements; try { await app .auth() .createUserWithEmailAndPassword(email.value, password.value); navigate("/dashboard") } catch(error) { alert(error) } }, [navigate]); return ( <div> <p>Register</p> <form onSubmit={handleSignup}> <label> Email <input name="email" type="email" placeholder="Email" /> </label> <label> Password <input name="password" type="password" placeholder="Password" /> </label> <button type="submit">Register</button> </form> </div> ) } export default Register
如果你需要保留原有withRouter写法,可选择降级到v5版本,执行命令:npm install react-router@5 react-router-dom@5
问题2:npm安装react-router时出现babel插件peer依赖警告
诱因
你项目中现有@babel/core版本低于7.13.0,而当前安装的@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining@7.16.0要求依赖的@babel/core版本必须为^7.13.0,版本范围不匹配触发了peer依赖警告。
修复方案
- 方案一:升级
@babel/core到符合要求的版本,执行命令:npm install @babel/core@^7.13.0 --save-dev - 方案二:如果暂时不需要使用该bugfix插件的能力,可直接忽略该警告,警告不会影响项目正常运行。
内容的提问来源于stack exchange,提问作者Bram
相关产品推荐
相关产品推荐

