繁体   English   中英

React Router6:将元素传递给私有路由时出现问题

[英]React Router6: issue while passing element to private route

我正在尝试将 PrivateRoute 组件创建为:

import { useStoreState } from 'easy-peasy';
import React, { Component } from 'react';
import { Navigate, Route } from 'react-router-dom';

// import styles from'./index.module.scss';

interface PrivateRouteProps {
  path: string;
  element: Component;
}
const PrivateRoute: React.FC<PrivateRouteProps> = ({
  path,
  element,
  children,
  ...props
}) => {
  const isLoggedIn = useStoreState((state: any) => state.user.isLoggedIn);

  if (!isLoggedIn) {
    return <Navigate to="/login" />;
  }

  return (
    <Route path={path} element={element} {...props}>
      {children}
    </Route>
  );
};
export default PrivateRoute;

这就是我尝试使用它的方式:

function App() {
  return (
    <div className={styles.app}>
      <Router>
        <Routes>
          <Route path="" element={<Home />}></Route>
          <Route path="login" element={<Login />}></Route>
          <PrivateRoute path="cohort" element={MyComponent}></PrivateRoute>
        </Routes>
      </Router>
    </div>
  );
}

但是在使用 PrivateRoute 时出现此错误: 在此处输入图像描述

我之前对element: React.ComponentType<any>解决了 typescript 错误,但随后出现新错误

错误:[PrivateRoute] 不是组件。 的所有子组件必须是 <Route> 或 <React.Fragment>

因此,对于 v6 react router,只有 Route 组件可以是 Routes 的子组件。 请参阅 v6 文档,您会看到身份验证模式是使用包装器组件来处理身份验证检查和重定向。

旧的 v5 模式将不再适用。

这就是您的PrivateRoute的样子。 我已经注释掉了之前的代码,以便您可以看到我所做的更改。

import { useStoreState } from "easy-peasy";
import React, { Component } from "react";
import { Navigate, Route } from "react-router-dom";

// import styles from'./index.module.scss';

interface PrivateRouteProps {
  path: string;
  element: React.ComponentType<any>;
  // element: Component;
}
// const PrivateRoute: React.FC<PrivateRouteProps> = ({
//   path,
//   element,
//   children,
//   ...props
// }) => {
const PrivateRoute = ({ children }: { children: JSX.Element }) => {
  const isLoggedIn = useStoreState((state: any) => state.user.isLoggedIn);

  if (!isLoggedIn) {
    return <Navigate to="/login" />;
  }

  // return (
  //   <Route path={path} element={element} {...props}>
  //     {children}
  //   </Route>
  // );

  return children;
};

export default PrivateRoute;

而且,您的App组件将如下所示

export function App() {
  return (
    <div>
      <Router>
        <Routes>
          <Route path="" element={<Home />}></Route>
          <Route path="login" element={<Login />}></Route>
          {/* <PrivateRoute path="cohort" element={MyComponent}></PrivateRoute> */}
          <Route
            path="cohort"
            element={
              <PrivateRoute>
                <MyComponent />
              </PrivateRoute>
            }
          />
        </Routes>
      </Router>
    </div>
  );
}

而且,这里是代码框https://codesandbox.io/s/reactrouterv6wayofdoingthings-0nmkg?file=/src/App.tsx的链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM