반응형
조건에 따라 모든 경로가 동적으로 로드될 때 경로로 리디렉션하는 방법?
이것은 컨텍스트에서 사용자 객체를 기준으로 라우트(Ract Router dom 5)를 로드하는 나의 코드다.
function App() {
return (
<UserContextProvider>
<BrowserRouter>
<Navigation/>
</BrowserRouter>
</UserContextProvider>
);
}
내비게이션 코드.여기서 나는 조건부로 경로를 적재한다.
function Navigation() {
const { contextState } = useUserContext();
const routes = contextState.user ? routesAuthenticated : routerUnauthenticated;
return (
<Switch>
{routes.map((route, index) => {
return (
<Route
key={index}
path={route.path}
exact={route.exact}
render={(props: RouteComponentProps) => (
<route.component name={route.name} {...props} {...route.props} />
)}
/>
);
})}
</Switch>
);
}
컨텍스트 사용자 객체를 기반으로 다른 경로를 로드하는 것을 볼 수 있을 겁니다.경로는 단순 구성 파일:
export const routerUnauthenticated: IRoute[] = [
{
path: '/register',
name: 'Register page',
component: RegisterPage,
exact: false,
},
{
path: '/login',
name: 'Login page',
component: LoginPage,
exact: false,
}...
문제는 내가 지금 가는 길이라는 것이다.http://localhost:3000/login
그리고 완전한 로그인에 성공한 후 나는 경로가 있는 빈 페이지를 얻었다.http://localhost:3000/login
로그인하기 전에 3개의 경로 로그인/등록/홈이 있다.로그인 후 5개의 경로 대시보드/프로파일이 있음...내가 하고자 하는 것은 로그인이 성공한 후에 하는 것이다./dashboard
경로. 하지만 동적 경로 로딩에 대한 내 생각 때문에 어떻게 항해해야 할지 모르겠어.
내 컨텍스트에서 로그인은 간단한 가짜 기능이다.
try {
setContextState({ type: ContextActions.LOGIN_IN_PROGRESS });
setTimeout(() => {console.log({ userId: 1, username: 'admin@admin.com' });
setContextState({ type: ContextActions.LOGIN_SUCCESS, payload: { user: { userId: 1, username: 'admin@admin.com' } } });
}, 3000);
} catch(error) {
setContextState({ type: ContextActions.LOGIN_ERROR });
}
왜 모든 루트를 다 싣지 않는 거지?사용자 지정 Route 구성 요소를 사용하여 contextState.user가 있는지 확인할 수 있으며, 인증되지 않은 사용자가 해당 경로로 이동할 경우 /login 또는 /register로 리디렉션되는 보호된 경로와 비슷한 종류.
이것은 널리 사용되고 있는 가장 일반적인 protectedRoute 성분이다.
const App = () => {
const { user } = useAuth();
return (
<Router>
<Route path="/public">
<Public />
</Route>
<Route path="/login">
<Login />
</Route>
<PrivateRoute path='/protected' user={user}>
<Protected />
</PrivateRoute>
</div>
</Router>
)
}
const PrivateRoute = ({ children, user, ...rest }) => (
<Route {...rest} render={({ location }) => {
return user === null
? <Redirect to={{
pathname: '/login',
state: { from: location }
}}
/>
: children
}} />
)
반응형
'Programing' 카테고리의 다른 글
VueRouter 인스턴스에서 경로 개체에 액세스하는 중 (0) | 2022.03.10 |
---|---|
TDD 중 Vue 인스턴스의 조롱 방법 (0) | 2022.03.10 |
python에서 float를 정수로 변환하는 가장 안전한 방법? (0) | 2022.03.10 |
대응: 위험하게 SetInner를 사용하여 삽입할 때 스크립트 태그가 작동하지 않음HTML (0) | 2022.03.10 |
잘못된 URL 매개 변수를 사용하여 404 페이지로 리디렉션하는 방법 (0) | 2022.03.10 |