使用react-router-dom 6.3.0时出现history读取错误求助
解决react-router-dom 6.3.0中搜索跳转时的history未定义错误
错误原因
react-router-dom v6 彻底移除了通过组件props传递history、location等路由对象的方式。你的Search组件试图解构props中的history,但该值为undefined,调用history.push时自然触发Cannot read properties of undefined (reading 'history')错误,同时URL无法更新。
修复方案
使用v6官方推荐的useNavigate钩子替代原有的history对象,同时调整路由配置确保跳转路径能正确匹配组件。
1. 修改Search组件,替换为useNavigate
更新Search.js代码,导入并使用useNavigate钩子:
import React, { useState, Fragment } from "react"; import MetaData from "../layout/MetaData"; import { useNavigate } from "react-router-dom"; // 新增导入useNavigate import "./Search.css"; const Search = () => { // 移除props中的history参数 const navigate = useNavigate(); // 初始化导航方法 const [keyword, setKeyword] = useState(""); const searchSubmitHandler = (e) => { e.preventDefault(); if (keyword.trim()) { navigate(`/products/${keyword}`); // 用navigate替代history.push } else { navigate("/products"); } }; return ( <Fragment> <form className="searchBox" onSubmit={searchSubmitHandler}> <input type="text" placeholder="Search a Product ..." onChange={(e) => setKeyword(e.target.value)} /> <input type="submit" value="Search" /> </form> </Fragment> ); }; export default Search;
2. 调整路由配置,支持搜索参数
在App.js的Routes中,修改Products的路由规则,使其支持可选的搜索关键词参数:
<Routes> <Route path='/' element={<Home/>} /> <Route path='/product/:id' element={<ProductDetails/>} /> <Route path='/products/:keyword?' element={<Products/>} /> {/* 新增可选参数:keyword? */} <Route path='/search' element={<Search/>} /> </Routes>
3. 在Products组件中获取搜索关键词(可选)
如果需要在Products组件中根据关键词筛选商品,可以使用useParams钩子获取参数:
import { useParams } from "react-router-dom"; const Products = () => { const { keyword } = useParams(); // 根据keyword执行商品筛选逻辑 }
效果验证
修改完成后,点击搜索按钮时,URL会正常跳转到/products/[关键词]或/products,同时不会再触发history未定义的错误。
内容的提问来源于stack exchange,提问作者Ujwal Gaonkar
相关产品推荐
相关产品推荐

