score:1

Accepted answer

You should only return one component per route and handle authentication within the routed component. Here an example, which handles your Header/Footer case.

function Authenticated ({component: Component, hasFooterHeader, ...rest}) {
  const authed = IsLoggedIn();
  let page = <>;
  if (hasFooterHeader) {
    page = (
      <>
        <Header />
        <Shell>
          <Component {...rest} />
        </Shell>
        <Footer />
      <>
    );
  } else {
    page = <Component {...rest} />;
  }
  return (
    <Route
      {...rest}
      render={(props) => authed === true
        ? page
        : <Redirect to={{pathname: '/login', state: {from: props.location}}} />}
    />
  )
}

And the Routing would look like this:

<Switch>
  <Route path="/login" exact component={Login} />
  <Route path="/SignUp" exact component={SignUp} />
  <Route path="/ForgotPassword" exact component={ForgotPassword} />
  <Route path="/ChangePassword" exact component={ChangePassword} />
  <Authenticated path="/startTest" exact component={StartTest} />
  <Authenticated path="/TestResult" exact component={TestResult} hasFooterHeader />
  <Authenticated path="/TestList" exact component={TestList} hasFooterHeader />
  <Authenticated path="/Home" exact component={Home} hasFooterHeader />
  <Authenticated path="/" exact component={Home} hasFooterHeader />
  <Authenticated component={GenericNotFound} hasFooterHeader />
  <Route component={GenericNotFound} />
</Switch>

score:0

When you use react route in app it's important to build clear and extendable code framework

I suggest you seal the Authenticated and Layout under route component

like baselayout.js in base then accountlayout, pagelayout extend base then read array of router like [ name :home, layout: pagelayout, auth: authed ] dynamic load router use js

it's not suitable we Auth under BrowserRouter with Switch

you can check umi.js enter link description here


Related Query

More Query from same tag