Programing

조건에 따라 모든 경로가 동적으로 로드될 때 경로로 리디렉션하는 방법?

c10106 2022. 3. 10. 21:55
반응형

조건에 따라 모든 경로가 동적으로 로드될 때 경로로 리디렉션하는 방법?

이것은 컨텍스트에서 사용자 객체를 기준으로 라우트(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
    }} />
)

참조URL: https://stackoverflow.com/questions/67628272/how-to-redirect-to-route-when-all-routes-are-loaded-dynamically-based-on-conditi

반응형