简体   繁体   English

嵌套条件路由渲染

[英]Nested conditional routes rendering

How can I include another conditional check before routing the user?如何在路由用户之前包含另一个条件检查? In my example, if isLoading is false , I want to render all the routes below but I also want to check if tokenValid for a few specific routes.在我的示例中,如果isLoadingfalse ,我想呈现下面的所有路由,但我还想检查一些特定路由的tokenValid是否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>)
}

If you want to make contionnal routing, you have to include the entire <Switch> in the condition.如果要进行连续路由,则必须在条件中包含整个<Switch> Here is an exemple for a authentification.下面是一个身份验证的例子。

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")
);

I handle auth like so using redux too!我也使用 redux 像这样处理身份验证!

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;

Should help!应该有帮助!

Daniel丹尼尔

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM