creating common header and sidebar across all the

2019-05-10 21:54发布

问题:

App.js

class App extends Component {
    render() {
    return (
      <Router history={history}>
        <Switch>
          <Route path="/" exact component={Login} />
          <div>
            <Header />
            <div className="main">
              <SideBar />
              <Route
                path="/dashboard"
                exact
                component={RequireAuth(Dashboard)}
              />
              <Route path="/profile" exact component={RequireAuth(Profile)} />
            </div>
          </div>
        </Switch>
      </Router>
   );
 }
}

Here i want Header and Sidebar to be common across all the pages while i change the route and i am getting the result but i think it is not a standard way to do so,please suggest and help me,that how should i create the common layout for some set of pages and another layout for other pages,like

 <Router history={history}>
  <Switch>
   <layout1>
    <Route path="/dashboard" exact component={RequireAuth(Dashboard)}/>
    <Route path="/profile" exact component={RequireAuth(Profile)} />
   </layout1>

   <layout2>
    <Route path="/otherinfo1" exact component={RequireAuth(OtherInfo1)}/>
    <Route path="/otherinfo2" exact component={RequireAuth(OtherInfo2)} />
   </layout2>
  </Switch>
 </Router>

i am using react router 4.2.2

and every time i login and redirect to dashboard, jquery functionality doesn't work, always i need to refresh the page to run jquery related stuffs(if could help)

回答1:

You could prefix, you two sets of routes with an identifier and set that as a Route path, All other routes can go inside the respective container Layout

<Router history={history}>
  <Switch>
   <Route path="/layout1" component={FirstContainer}/>
   <Route path="/layout2" component={SecondContainer}/>
  </Switch>
</Router>

Then you FirstContainer would be like

const FirstContainer = ({match}) => (
    <div>
         {/* other stuff */}
         <Route path={`${match.path}/dashboard`} exact component={RequireAuth(Dashboard)}/>
         <Route path={`${match.path}/profile`} exact component={RequireAuth(Profile)} />
         {/* other stuff */}
    </div>

)

and SecondContainer

const SecondContainer = ({match}) => (
    <div>
         {/* other stuff */}
         <Route path={`${match.path}/otherinfo1`} exact component={component={RequireAuth(OtherInfo1)}}/>
         <Route path={`${match.path}/otherinfo2`} exact component={RequireAuth(OtherInfo2)} />
         {/* other stuff */}
    </div>

)