CoreUI React Re-Routing после входа в систему не работает должным образом - PullRequest
0 голосов
/ 19 декабря 2018

Итак, я просто исправил свое приложение, чтобы после успешного входа в систему отображалась домашняя страница.Однако после этого остальная часть моего маршрута, казалось, волшебным образом исчезла.Вот соответствующий код:

DefaultLayout.js

class DefaultLayout extends Component {
  constructor(props){
    super(props);
    this.state = {
       name:'',
       redirect: false,
   };
}

componentDidMount() {
     let data = JSON.parse(sessionStorage.getItem('userData'));
     console.log(data);
}

  render() {
    if(!sessionStorage.getItem('userData') || this.state.redirect){
    return (<Redirect to={'/404'}/>)
}

    return (
      <div className="app">
        <AppHeader fixed>
          <DefaultHeader />
        </AppHeader>
        <div className="app-body">
          <AppSidebar fixed display="lg">
            <AppSidebarHeader />
            <AppSidebarForm />
            <AppSidebarNav navConfig={navigation} {...this.props} />
            <AppSidebarFooter />
            <AppSidebarMinimizer />
          </AppSidebar>
          <main className="main">
            <AppBreadcrumb appRoutes={routes}/>
            <Container fluid>
              <Switch>
                {routes.map((route, idx) => {
                    return route.component ? (<Route key={idx} path={route.path} exact={route.exact} name={route.name} render={props => (
                        <route.component {...props} />
                      )} />)
                      : (null);
                  },
                )}
                <Redirect from="/home" to="/dashboard" />
              </Switch>
            </Container>
          </main>

Login.js

class Login extends Component {
  constructor(props) {
    super(props);
       this.state = {
       loginError: false,
       redirect: false
};
this.signup = this.signup.bind(this);
}
signup(res, type) {
  let postData;
  if (type === 'google' && res.w3.U3) {
  postData = {
    email: res.profileObj.email,
    name: res.profileObj.name,
    googleId: res.profileObj.googleId,
    googleAccessToken: res.Zi.access_token,
    googleImageURL: res.profileObj.imageURL
  };
 }


if (postData) {
  PostData('v1/zuulusers', postData).then((result) => {
     let responseJson = result;
     sessionStorage.setItem("userData", JSON.stringify(responseJson));
     this.setState({redirect: true});
  });
  } else {}
}
render() {

  if (this.state.redirect || sessionStorage.getItem('userData')) {
    return (<Redirect to={'/home'}/>)
}
const responseGoogle = (response) => {
  console.log("google console");
  console.log(response);
  this.signup(response, 'google');
}

    return (


      <div className="app flex-row align-items-center">
        <Container>
          <Row className="justify-content-center">
            <Col md="5">
              <CardGroup>
                <Card className="text-white py-5 d-md-down-none" style={{ width: '44%' }}>
                  <CardBody className="text-center">
                    <div>
                      <h2>Login if you dare</h2>
                      <img src="https://s3.amazonaws.com/whatif-assets-cdn/images/asset_1+copy2.png" alt="zuul logo" id="zuul_logo" className="mx-auto d-block rounded img-avatar"/>
                          <GoogleLogin
                            clientId="24656564867-3issjp4bq0gsr05banuomnniilngiicc.apps.googleusercontent.com"
                            buttonText="Login with Google"
                            onSuccess={responseGoogle}
                            onFailure={responseGoogle}
                          />
                    </div>

App.js

class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <Switch>
          <Route  path="/home" name="Home Page" component={DefaultLayout} />
          <Route exact path="/register" name="Register Page" component={Register} />
          <Route exact path="/404" name="Page 404" component={Page404} />
          <Route exact path="/500" name="Page 500" component={Page500} />
          <Route exact path="/" name="login" component={Login} />
        </Switch>
      </BrowserRouter>
    );
  }
}

А потомэто небольшой фрагмент кода, чтобы показать, как настроена маршрутизация в CoreUI:

rout.js

const LoadingButtons = Loadable({
  loader: () => import('./views/Buttons/LoadingButtons'),
  loading: Loading,
});

const Charts = Loadable({
  loader: () => import('./views/Charts'),
  loading: Loading,
});

const Dashboard = Loadable({
  loader: () => import('./views/Dashboard'),
  loading: Loading,
});
const routes = [
  { path: '/', name: 'Login', component: Login, exact: true },
  { path: '/home', name: 'Home', component: DefaultLayout, exact: true},
  { path: '/dashboard', name: 'Dashboard', component: Dashboard },

По какой-то причине после загрузки домашней страницы она не загружаетсялюбая из других страниц.Они просто появляются пустыми, но путь определяется в URL.Не уверен, что я делаю неправильно в маршрутизации.

1 Ответ

0 голосов
/ 18 февраля 2019

Вместо того, чтобы проверять DefaultLayout, который является контейнером для всех навигационных систем, попробуйте сделать это внутри, поскольку вы перенаправляете маршруты туда.

<Switch>
 {routes.map((route, idx) => {
   return route.component ? (
     <Route
       key={idx}
       path={route.path}
       exact={route.exact}
       name={route.name}
       render={props =>
        sessionStorage.getItem('userData') !== null (
         <route.component {...props} />  ) : (
         <Redirect to={{ pathname: "/login" }} /> ) //your route here
       }
      />
     ) : null;
  })}
 <Redirect from="/" to="/dashboard" />
</Switch>

Здесь все маршруты проверяются на аутентификацию.Если вы вошли в систему, то пользователь может получить к нему доступ, иначе перенаправить на логин или 404. Как вам больше нравится.

...