React中useParams()报TypeError: useContext(...) is undefined如何解决?
错误产生原因
核心错误来自路由上下文注入失败,具体有2个触发点:
- 最主要原因是App.js中路由组件渲染方式错误:你直接通过
route.component()调用执行组件函数,而非将其作为React元素交由Route组件渲染,导致组件执行时不在Router提供的路由Context树范围内。react-router的所有钩子都依赖顶层Router注入的Context,脱离上下文后useContext(Context)自然返回undefined,调用其match属性就触发类型错误。 - 次要问题是routes.js存在语法错误:
export const routes: [中的冒号属于TypeScript类型声明语法,在普通JS文件中会导致解析异常,你当前项目未标注是TS项目,该写法不合法。
修复方案
- 修正App.js中路由组件的渲染逻辑
将原来直接调用组件的写法:
{routes.map((route) => ( <Route exact path={route.path}> {route.component()} </Route> ))}
修改为以下任意一种合法渲染方式即可:
方式一:作为子元素渲染
{routes.map((route, index) => ( <Route exact path={route.path} key={index}> <route.component /> </Route> ))}
方式二:使用Route的component属性
{routes.map((route, index) => ( <Route exact path={route.path} key={index} component={route.component} /> ))}
- 修正routes.js的语法错误
将冒号改为等号,修正后的完整代码:
import Dashboard from "../pages/Dashboard"; import UserDetails from "../pages/UserDetails"; export const routes = [ { name: "Dashboard", path: "/dashboard", component: Dashboard, access: "public", }, { name: "User details", path: "/user/:id", component: UserDetails, access: "private", }, ];
修复完成后重启项目即可正常通过useParams获取路由参数。
内容的提问来源于stack exchange,提问作者Abdurahman Shiine
相关产品推荐
相关产品推荐

