오류: [PrivateRoute]가 컴포넌트가 아닙니다 . 의 모든 구성 요소는 또는이어야 합니다 .
React Router v6를 사용하고 있으며 응용 프로그램의 개인 경로를 만들고 있습니다.
PrivateRoute.js 파일에는
import React from 'react';
import {Route,Navigate} from "react-router-dom";
import {isauth} from 'auth'
function PrivateRoute({ element, path }) {
const authed = isauth() // isauth() returns true or false based on localStorage
const ele = authed === true ? element : <Navigate to="/Home" />;
return <Route path={path} element={ele} />;
}
export default PrivateRoute
file route.js에는 다음과 같이 기술되어 있습니다.
...
<PrivateRoute exact path="/" element={<Dashboard/>}/>
<Route exact path="/home" element={<Home/>}/>
리액트 라우터의 인증 예(StackBlitz, 파일 App.tsx)도 같은 예에서 확인했습니다.
제가 놓친 게 있나요?
나는 오늘 같은 문제에 부딪혔고 Andrew Luca의 매우 유용한 기사를 바탕으로 다음과 같은 해결책을 생각해냈다.
PrivateRoute.js의 경우:
import React from 'react';
import { Navigate, Outlet } from 'react-router-dom';
const PrivateRoute = () => {
const auth = null; // determine if authorized, from context or however you're doing it
// If authorized, return an outlet that will render child elements
// If not, return element that will navigate to login page
return auth ? <Outlet /> : <Navigate to="/login" />;
}
App.js (예시로 다른 페이지에 남겨두었습니다) :
import './App.css';
import React, {Fragment} from 'react';
import {BrowserRouter as Router, Route, Routes} from 'react-router-dom';
import Navbar from './components/layout/Navbar';
import Home from './components/pages/Home';
import Register from './components/auth/Register'
import Login from './components/auth/Login';
import PrivateRoute from './components/routing/PrivateRoute';
const App = () => {
return (
<Router>
<Fragment>
<Navbar/>
<Routes>
<Route exact path='/' element={<PrivateRoute/>}>
<Route exact path='/' element={<Home/>}/>
</Route>
<Route exact path='/register' element={<Register/>}/>
<Route exact path='/login' element={<Login/>}/>
</Routes>
</Fragment>
</Router>
);
}
위의 라우팅에서는 프라이빗루트가 다음과 같습니다
<Route exact path='/' element={<PrivateRoute/>}>
<Route exact path='/' element={<Home/>}/>
</Route>
인가가 성공하면 요소가 표시됩니다.그렇지 않으면 로그인 페이지로 이동합니다.
만.Route컴포넌트는 의 자식일 수 있습니다.Routes리다이렉트를 을 알 수 v6 문서를 따르면 인증 패턴은 래퍼 컴포넌트를 사용하여 인증 체크와 리다이렉트를 처리하는 것을 알 수 있습니다.
function RequireAuth({ children }: { children: JSX.Element }) { let auth = useAuth(); let location = useLocation(); if (!auth.user) { // Redirect them to the /login page, but save the current location they were // trying to go to when they were redirected. This allows us to send them // along to that page after they login, which is a nicer user experience // than dropping them off on the home page. return <Navigate to="/login" state={{ from: location }} />; } return children; } ... <Route path="/protected" element={ <RequireAuth> <ProtectedPage /> </RequireAuth> } />
custom의 .Route이치노코드/로직을 사용하여 업데이트된 v6 패턴은 다음과 같습니다.
const PrivateRoute = ({ children }) => {
const authed = isauth() // isauth() returns true or false based on localStorage
return authed ? children : <Navigate to="/Home" />;
}
그리고 사용하기 위해서
<Route
path="/dashboard"
element={
<PrivateRoute>
<Dashboard />
</PrivateRoute>
}
/>
코드의 행을 줄여, 보다 읽기 쉽고 아름답게 하기 위한 보완 기능.
이건 그냥 댓글일 수도 있는데 제가 포인트가 부족해서 답변으로 넣겠습니다.
Dallin의 대답은 맞지만 Drew의 대답이 더 낫습니다!그리고 미학에 대한 Drew의 답변을 완성하기 위해 저는 어린이 대신 부품을 소품으로 사용하는 개인 컴포넌트를 만들 것을 권장합니다.
개인 루트 파일/컴포넌트의 매우 기본적인 예:
import { Navigate } from 'react-router-dom';
const Private = (Component) => {
const auth = false; //your logic
return auth ? <Component /> : <Navigate to="/login" />
}
루트 파일의 예:
<Routes>
<Route path="/home" element={<Home />} />
<Route path="/user" element={<Private Component={User} />} />
</Routes>
이 레시피가 이 레시피를 만드는 방법이 아니라는 걸PirvateRoute다만, 새로운 메뉴얼에서는, 리액트 라우터 v6로 이 패턴을 처리하기 위해서, 약간 다른 어프로치를 추천하고 있습니다.
<Route path="/protected" element={<RequireAuth><ProtectedPage /></RequireAuth>} />
import { Navigate, useLocation } from "react-router";
export const RequireAuth: React.FC<{ children: JSX.Element }> = ({ children }) => {
let auth = useAuth();
let location = useLocation();
if (!auth.user) {
return <Navigate to="/login" state={{ from: location }} />;
}
return children;
};
이 를 더 .ProtectedPage필요한 경우 자동으로 사용할 수 있습니다.
상세한 것에 대하여는, 메뉴얼과 예를 참조해 주세요.또, 실장 상세에 관한 마이클 잭슨의 노트도 확인해 주세요.
라우터 컴포넌트를 엘리먼트프롭으로 설정하기만 하면 됩니다.
<Routes>
<Route exact path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/dashboard" element={<Dashboard />} />
</Routes>
v5에서 업그레이드하는지 확인할 수도 있습니다.
프로젝트에서 PrivateRoute 구성 요소를 제거하고 App.js 파일에서 다음 코드를 사용합니다.
import {Navigate} from "react-router-dom";
import {isauth} from 'auth'
...
<Route exact path="/home" element={<Home/>}/>
<Route exact path="/" element={isauth ? <Dashboard/> : <Navigate to="/Home" />}/>
2022년에 저는 다음과 같은 일을 했습니다.
// routes.tsx
import { lazy } from "react";
import { Routes, Route } from "react-router-dom";
import Private from "./Private";
import Public from "./Public";
const Home = lazy(() => import("../pages/Home/Home"));
const Signin = lazy(() => import("../pages/Signin/Signin"));
export const Router = () => {
return (
<Routes>
<Route path="/" element={Private(<Home />)} />
<Route path="/signin" element={Public(<Signin />)} />
</Routes>
);
};
// Private.tsx
import { Navigate } from "react-router-dom";
import { useEffect, useState } from "react";
function render(c: JSX.Element) {
return c;
}
const Private = (Component: JSX.Element) => {
const [hasSession, setHasSession] = useState<boolean>(false);
useEffect(() => {
(async function () {
const sessionStatus = await checkLoginSession();
setHasSession(Boolean(sessionStatus));
})();
}, [hasSession, Component]);
return hasSession ? render(Component) : <Navigate to="signin" />;
};
export default Private;
이게 도움이 됐으면 좋겠네요!
반응 라우터 v6, 통사당:
{auth && (
privateRoutes.map(route =>
<Route
path={route.path}
key={route.path}
element={auth.isAuthenticated ? <route.component /> : <Navigate to={ROUTE_WELCOME_PAGE} replace />}
/>
)
)}
모든 답변을 시도했지만 항상 다음 오류가 표시되었습니다.
오류: [PrivateRoute]가 컴포넌트가 아닙니다.의 모든 컴포넌트 자녀는 또는 <React>여야 합니다.프래그먼트>
하지만 해결책을 찾았습니다.)-
PrivateRoute.js 파일:
import React from "react"; import { Navigate } from "react-router-dom";
import {isauth} from 'auth'
const PrivateRoute = ({ children }) => {
const authed = isauth()
return authed ? children : <Navigate to={"/Home" /> };
export default ProtectedRoute;
route.js 파일:
<Route
path="/"
element={
<ProtectedRoute >
<Dashboard/>
</ProtectedRoute>
}
/>
<Route exact path="/home" element={<Home/>}/>
Children of Routes는 루트 요소가 되어야 Protected Route를 변경할 수 있습니다.
export type ProtectedRouteProps = {
isAuth: boolean;
authPath: string;
outlet: JSX.Element;
};
export default function ProtectedRoute({
isAuth,
authPath,
outlet,
}: ProtectedRouteProps) {
if (isAuth) {
return outlet;
} else {
return <Navigate to={{pathname: authPath}} />;
}
}
그리고 이렇게 사용하세요.
const defaultProps: Omit<ProtectedRouteProps, 'outlet'> = {
isAuth: //check if user is authenticated,
authPath: '/login',
};
return (
<div>
<Routes>
<Route path="/" element={<ProtectedRoute {...defaultProps} outlet={<HomePage />} />} />
</Routes>
</div>
);
개인 루트를 작성하는 간단한 방법은 다음과 같습니다.
import React from 'react'
import { Navigate } from 'react-router-dom'
import { useAuth } from '../../context/AuthContext'
export default function PrivateRoute({ children }) {
const { currentUser } = useAuth()
if (!currentUser) {
return <Navigate to='/login' />
}
return children;
}
Dashboard 컴포넌트에 개인 루트를 추가할 경우 다음과 같이 이 개인 루트를 적용할 수 있습니다.
<Routes>
<Route exact path="/" element={<PrivateRoute><Dashboard /></PrivateRoute>} />
</Routes>
장기의 요소
<Router>
<div>
<Navbar totalItems={cart.total_items}/>
<Routes>
<Route exact path='/'>
<Route exact path='/' element={<Products products={products} onAddToCart={handleAddToCart}/>}/>
</Route>
<Route exact path='/cart'>
<Route exact path='/cart' element={<Cart cart={cart}/>}/>
</Route>
</Routes>
</div>
</Router>
헤더는 모든 페이지에 남습니다.
import React from 'react';
import {
BrowserRouter,
Routes,
Route
} from "react-router-dom";
const Header = () => <h2>Header</h2>
const Dashboard = () => <h2>Dashboard</h2>
const SurveyNew = () => <h2>SurveyNew</h2>
const Landing = () => <h2>Landing</h2>
const App = () =>{
return (
<div>
<BrowserRouter>
<Header />
<Routes >
<Route exact path="/" element={<Landing />} />
<Route path="/surveys" element={<Dashboard />} />
<Route path="/surveys/new" element={<SurveyNew/>} />
</Routes>
</BrowserRouter>
</div>
);
};
export default App;
<Route path='/' element={<Navigate to="/search" />} />
개인 루트에 다음 함수를 사용할 수 있습니다.
<Route exact path="/login" element={NotAuth(Login)} />
<Route exact path="/Register" element={NotAuth(Register)} />
function NotAuth(Component) {
if (isAuth)
return <Navigate to="/" />;
return <Component />;
}
'react-router-dom' : '^6.3.0'을 사용하고 있습니다.이렇게 해서 저는
PrivateRoute 컴포넌트와 루트
import {Route} from "react-router-dom";
const PrivateRoute = ({ component: Compontent, authenticated }) => {
return authenticated ? <Compontent /> : <Navigate to="/" />;
}
<Route
path="/user/profile"
element={<PrivateRoute authenticated={true} component={Profile} />} />
오류 "Navigate"는 <Route> 컴포넌트가 아닙니다.<Routes>의 모든 컴포넌트 자식은 <Route> 또는 <React>여야 합니다.fragment > )는 다음과 같은 방법으로 해결할 수 있습니다.
디폴트 페이지는 일치하는 라우터가 없는 경우입니다.Default Page로 이동합니다.여기서 <Route index element={} /> 를 사용하여,
<Navigate to={window.location.pathname + '/kanban'}/>
<Routes>
<Route path={'/default'} element={<DefaultPage/>}/>
<Route path={'/second'} element={<SecondPage/>}/>
{/* <Navigate to={window.location.pathname + '/kanban'}/> */}
<Route index element={<DefaultPage/>} />
</Routes>
import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<h1>home page</h1>} />
<Route path="/seacrch" element={<h1>seacrch page</h1>} />
</Routes>
</Router>
);
}
export default App;
언급URL : https://stackoverflow.com/questions/69864165/error-privateroute-is-not-a-route-component-all-component-children-of-rou
'programing' 카테고리의 다른 글
| 반응 - useState - setTimeout 함수에 최신 상태 값이 없는 이유는 무엇입니까? (0) | 2023.03.15 |
|---|---|
| 프로바이더에서 $window에 접속하는 방법 (0) | 2023.03.15 |
| json 파일을 가져오는 동안 Typescript 컴파일러 오류 발생 (0) | 2023.03.15 |
| JSON을 설정합니다.NET에서 DataContract/DataMember 속성을 무시합니다. (0) | 2023.03.15 |
| jQuery - .getjson VS .ajax json (0) | 2023.03.15 |