reactjs React Router DOM:自定义路由组件不工作

n7taea2i  于 2023-06-05  发布在  React
关注(0)|答案(1)|浏览(135)

我的应用程序总共有5条路线,其中4条我需要一个条件为真,才能让用户访问这些路线。所以我想为上述路线创建检查。我制作了PublicRoute和PrivateRoute组件

import { Route } from 'react-router-dom';

const PublicRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={(props) => <Component {...props} />} />
);  

export default PublicRoute
import { Route, Redirect } from 'react-router-dom';

const PrivateRoute = ({ component: Component, isAuthenticated, ...rest }) => (
  <Route
    {...rest}
    render={(props) =>
      isAuthenticated ? (
        <Component {...props} />
      ) : (
        <Redirect to="/" />
      )
    }
  />
);

export default PrivateRoute

我的app.js

import { Routes } from "react-router-dom"
import PublicRoute from "./components/PublicRoute"

const App = () => {
  return (
    <>
      <Routes>

        <PublicRoute
          exact
          path="/"
          component={Com}
        />

      </Routes>
    </>
  )
}

export default App

const Com=()=>(
  <>
  <h1>Hi</h1>
  </>
)

目前我得到这个错误

not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>
    at invariant (history.ts:48

鉴于我返回一个路由组件,我不能完全理解为什么这个错误弹出。最终我想要一种方法来执行检查并保持代码干净,如果有其他有效的方法,请让我知道!

8ehkhllq

8ehkhllq1#

Routes组件需要一个文本Route组件作为子组件。
对我很有效-
公共路线

import { Route } from "react-router-dom";

const PublicRoute = ({ component: Component, ...rest }) => (
  <Component {...rest} />
);

export default PublicRoute;

App.js

import { BrowserRouter, Routes, Route } from "react-router-dom";
import PublicRoute from "./PublicRoute";

const App = () => {
  return (
    <BrowserRouter>
      <Routes>
        <Route
          exact
          path="/"
          element={
            <PublicRoute component={Com} msg={"there"} person={"sandy"} />
          }
        />
      </Routes>
    </BrowserRouter>
  );
};

export default App;

const Com = ({ msg, person }) => (
  <>
    <h1>
      Hi {msg} {person}
    </h1>
  </>
);

相关问题