嵌套条件路由渲染

时间:2020-01-07 19:28:37

标签: reactjs react-router

在路由用户之前,如何包括其他条件检查?在我的示例中,如果isLoadingfalse,我想渲染下面的所有路由,但是我也想检查tokenValid是否有一些特定的路由。

if (!isLoading) {
  return (
    <MuiThemeProvider theme={theme}>
      {
        showConnectionWarning &&
        <ConnectionWarning isOnline={isOnline} />
      }
      <Switch>

        <Route path="/authverify/:token" component={Login} />
        {/* Logged in forwards redirect */}
        {loggedIn && (
          <Redirect exact from="/" to={authRedirectTarget} />
        )}
        {/* Login */}
        <Route exact path="/" component={Login} />
        <Route path="/signup" component={Login} />
        <Route path="/signup-info/:token" component={Login} />
        {/* Non-auth redirect */}
        {!loggedIn && (
          <Redirect
            to={{ pathname: '/', state: { from: location } }} />
        )}

        {tokenValid && (
          <Route exact path="/releases" component={ReleasesView} />
          <Route path="/playlists/:id" component={PlaylistDetail} />
          <Route path="/playlists" component={Playlist} />
          <Route path="/account" component={AccountView} />
        )}

        <Route
          path="/search/:category?/:profile?"
          component={Search} />
        <Route component={Fallback} />
      </Switch>

    </MuiThemeProvider>
  );

}
else {
  return (<h1></h1>)
}

2 个答案:

答案 0 :(得分:0)

如果要进行路由选择,则必须在条件中包括整个<Switch>。这是认证的一个例子。

import React from "react";
import ReactDOM from "react-dom";
import { createBrowserHistory } from "history";
import { Router, Route, Switch, Redirect } from "react-router-dom";

// core components
import Admin from "layouts/Admin.js";
import SignIn from "layouts/SignIn";

const hist = createBrowserHistory();
const loggedRoutes = () => (
  <Switch>
    <Route path="/" component={SignIn} />
    <Route path="/admin" component={Admin} />
    <Redirect from="/admin" to="/admin/aboutUs/whatWeDo" />
  </Switch>
);
const routes = () => (
  <Switch>
    <Route path="/" component={SignIn} />
    <Route path="/login" component={Admin} />
    <Redirect from="/" to="/login" />
  </Switch>
);
ReactDOM.render(
  <Router history={hist}>
    {checkIfAuth? loggedRoutes():routes()}
  </Router>,
  document.getElementById("root")
);

答案 1 :(得分:0)

我也使用redux来处理auth!

import React from "react";
import { Switch, Route } from "react-router-dom";

// REDUX STORE
import { connect } from "react-redux";
import { getAuthenticated, getPermissions } from "../modules/user/userReducer";

// CUSTOM COMPONENTS
import Home from "./Home";
import SpecialPage from "./SpecialPage";
import SpecialPageTwo from "./SpecialPageTwo";

const anAuthenticatedRoute = props => {
  if (!props.authenticated) return <Elements.LoginPrompt title = {props.title} />;
  if (props.permission && !props.permissions.includes(props.permission)) return <div className = "non-authenticated">Nice Try, But You Do Not Have Authenticated For This Page ...</div>;
  return <Route {...props} />;
};

const mapStateToPropsAuth = state => ({
  authenticated: getAuthenticated(state),
  permissions: getPermissions(state)
});

const AuthenticatedRoute = connect(mapStateToPropsAuth)(anAuthenticatedRoute);

const Routes = () => {
  return (
    <div className = "page">
      <Switch location = {window.location}>
        <Route exact path = "/" component = {Home} />
        <Route path = "/home" component = {Home} />
        <AuthenticatedRoute
          title = "My Special Page"
          path = "/my-special-page"
          component = {SpecialPage} />
        <AuthenticatedRoute
          title = "My Special Page Two"
          permission = "access:admin"
          path = "/my-special-page-two"
          component = {SpecialPage} />
      </Switch>
    </div>
  );
};

export default Routes;

应该帮助!

丹尼尔