如果react-router-dom中的url有错误参数,请添加路径

问题描述 投票:0回答:1
import { Provider } from 'jotai'
import React from 'react'
import ReactDOM from 'react-dom/client'
import { RouterProvider, createBrowserRouter } from 'react-router-dom'
import App from './App.tsx'
import Auth from './Auth.tsx'
import NewPass from './NewPass.tsx'
import ResetPassword from './ResetPassEmail.tsx'
import './index.css'

const router = createBrowserRouter([
  {
    path: "/",
    element: <Auth />,
  },
  {
    path: "/chatroom",
    element: <App />,
  },
  {
    path: "/psdResetEmail",
    element: <ResetPassword />,
  },
  {
    path: "/psdReset/:access_token=:access_token&token_type=:token_type&type=:type",
    element: <NewPass />,
  },
  {
    path: "/psdReset/:error=:error&error_code=:error_code&error_description=:error_description",
    element: <Auth />,
  },
]);

ReactDOM.createRoot(document.getElementById("root")!).render(
  <React.StrictMode>
    <Provider>
      <RouterProvider router={router} />
    </Provider>
  </React.StrictMode>
);

我目前正在使用此方法创建路由器,但是当我尝试为

access_token
error
创建新路径时遇到错误,但返回 404 错误。

错误 URL 如下所示:

"http://localhost:5173/psdReset#error=unauthorized_client&error_code=401&error_description=Email+link+is+invalid+or+has+expired"

access_token
URL 看起来相同,但带有
access_token
参数。

我正在尝试使用 URL 哈希。

javascript url react-router-dom
1个回答
0
投票

Route
组件的
path
属性仅使用 URL 路径部分进行路由匹配,添加 hash/queryString 不起作用,实际上会破坏路由匹配。

我建议创建一个可以读取哈希/查询字符串并有条件地渲染路由组件的组件,或者在没有“匹配”的情况下发出后退导航。

示例:

const PasswordReset = () => {
  const navigate = useNavigate();
  const { hash } = useLocation();
  
  // Create a URLSearchParams object from the hash value
  const searchParams = React.useMemo(() => new URLSearchParams(hash), [hash]);

  // Unpack any token values
  const accessToken = searchParams.get("access_token");
  const tokenType = searchParams.get("token_type");

  // Unpack any error values
  const error = searchParams.get("error");
  const errorCode = searchParams.get("error_code");
  const errorDescription = searchParams.get("error_description");

  // Compute which component type you want to render
  const isNewPass = accessToken && tokenType;
  const isAuth = error && errorCode && errorDescription;

  useEffect(() => {
    // If no "match" then navigate back
    if (!(isNewPass || isAuth)) {
      navigate(-1);
    }
  }, [isNewPass, isAuth, navigate]);

  // Render appropriate "match"
  if (isNewPass) {
    return <NewPass />;
  } else if (isAuth) {
    return <Auth />;
  }

  // No "match" render null
  return null;
};
const router = createBrowserRouter([
  {
    path: "/",
    element: <Auth />,
  },
  {
    path: "/chatroom",
    element: <App />,
  },
  {
    path: "/psdResetEmail",
    element: <ResetPassword />,
  },
  {
    path: "/psdReset",
    element: <PasswordReset />,
  },
]);
© www.soinside.com 2019 - 2024. All rights reserved.