我正在尝试在我的项目中实现 JWT,一篇文章提供了一个很好的解决方案:
https://dev.to/sanjayttg/jwt-authentication-in-react-with-react-router-1d03.
Github: https://github.com/sanjay-arya/react-auth-demo
我相信这篇文章很好地解释了它并提供了源代码,所以我不会在这里重复它,但基本上它创建了一个 Auth 上下文,为所有路由提供令牌信息,并允许访问用户是否有令牌的路由。它还有一个登录和注销系统,可以删除/创建令牌
提供的代码可以正常工作。当我想在注销后将用户重定向到 /login 页面而不是 / 页面时,就会出现问题。例如我将导航(“/”,{替换:true})更改为导航(“/登录”,{替换:true});在 Logout.jsx 中。
我收到此错误:
react-router-dom.js?v=7652cf65:202 Uncaught Error: Could not find a matching route for errors on route IDs: 2
at invariant (react-router-dom.js?v=7652cf65:202:11)
at _renderMatches (react-router-dom.js?v=7652cf65:3167:33)
at useRoutesImpl (react-router-dom.js?v=7652cf65:3033:25)
at DataRoutes (react-router-dom.js?v=7652cf65:3422:10)
at renderWithHooks (react-dom_client.js?v=7652cf65:12171:26)
at updateFunctionComponent (react-dom_client.js?v=7652cf65:14577:28)
at beginWork (react-dom_client.js?v=7652cf65:15912:22)
at HTMLUnknownElement.callCallback2 (react-dom_client.js?v=7652cf65:3674:22)
at Object.invokeGuardedCallbackDev (react-dom_client.js?v=7652cf65:3699:24)
at invokeGuardedCallback (react-dom_client.js?v=7652cf65:3733:39)
Show 19 more frames
console.js:213 The above error occurred in the <DataRoutes> component:
at DataRoutes (http://localhost:5173/node_modules/.vite/deps/react-router-dom.js?v=7652cf65:3419:5)
at Router (http://localhost:5173/node_modules/.vite/deps/react-router-dom.js?v=7652cf65:3491:15)
at RouterProvider (http://localhost:5173/node_modules/.vite/deps/react-router-dom.js?v=7652cf65:3375:5)
at Routes (http://localhost:5173/src/routes/index.jsx?t=1712483351401:26:7)
at AuthProvider (http://localhost:5173/src/provider/authProvider.jsx:21:3)
at App
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
这是一个未捕获的错误,但即使将 errorElement 添加到路由中,错误仍然存在。即使如此,我仍然不知道为什么会出现错误。我已经尝试解决这个问题几个小时但没有成功。
检查您是否正确定义了路线