Как перенаправить приватный маршрут в React?

#reactjs #redirect #react-router #react-router-dom

#reactjs #перенаправление #react-маршрутизатор #react-router-dom

Вопрос:

У меня проблема с моим компонентом PrivateRoute. Предполагается перенаправить пользователя на определенную страницу в случае определенных обстоятельств, но это не так. После входа в систему мое условие работает, но я не перенаправлен на правильную страницу. Я просто вижу /# , какое перенаправление по умолчанию из b2c я использую.

Компонент:

 const PrivateRoute: React.FC<PrivateRouteProps> = (props: PrivateRouteProps) => {
  const { authStatus } = props;
  ...
  if (authStatus === AuthStatus.SomeRole) {
    // conditional is working
    return <Route exact path="/specificUrl" render={() => <Redirect to="/specificUrl" />} />;
  }
  ...
};
  

Мое приложение:

 const App: React.FC = () => (
  <Suspense fallback={<Loader />}>
    <Switch>
      ...
      <PrivateRoute path="/specificUrl" component={SpecificComponent} />
      ...
    </Switch>
  </Suspense>
);
  

Что я делаю не так? Если я изменю код на этот:

 if (authenticationStatus === AuthenticationStatus.SignedInNotInPilot) {
  return <Redirect to="/specificUrl" />;
  // return <Route exact path="/specificUrl" render={() => <Redirect to="/specificUrl" />} />;
}
  

Я перенаправлен на, /specificUrl но SpecificComponent не загружается.

Но если я изменю код на этот SpecificComponent , он загружается, но мне приходится перенаправлять вручную:

 if (authenticationStatus === AuthenticationStatus.SignedInNotInPilot) {
  return <Route exact path="/specificUrl" render={() => <SpecificComponent />} />;
  // return <Redirect to="/specificUrl" />;
  // return <Route exact path="/specificUrl" render={() => <Redirect to="/specificUrl" />} />;
}
  

Ответ №1:

Ваша первая логика работает, но для перенаправления вы можете попробовать вывести { withRouter } из react-router-dom, затем обернуть им свой компонент при экспорте как компонент более высокого порядка. Это даст вам доступ к реквизиту истории, затем вы можете использовать историю для перенаправления с помощью history.push(‘/specificUrl’)

 import {withRouter} from 'react-router-dom'

const PrivateRoute: React.FC<PrivateRouteProps> = (props: PrivateRouteProps) => {
  const { authStatus, history } = props;
  ...
  if (authStatus === AuthStatus.SomeRole) {
    // conditional is working
    return <Route exact path="/specificUrl" render={() => history.push('/specificUrl') />} />;
    // or just history.push('/specificUrl') should work as well
  }
  ...
};

export default withRouter(PrivateRoute)  
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>