使用react路由器在所有页面上创建公共标题和侧边栏

时间:2017-11-16 10:36:59

标签: reactjs redux react-router react-redux react-router-v4

  

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

在这里,我希望Header和Sidebar在所有页面中都是通用的,而我改变路线并获得结果,但我认为这不是一种标准方式,请建议并帮助我,我应该如何创建公共布局  一些页面和其他页面的另一个布局,如

 <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>
  

我正在使用react router 4.2.2

每次登录并重定向到仪表板时,jquery功能都不起作用,总是需要刷新页面来运行jquery相关的东西(如果有帮助的话)

1 个答案:

答案 0 :(得分:2)

您可以使用前缀,两组带有标识符的路由并将其设置为路径路径,所有其他路由可以进入相应的容器布局

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

然后你FirstContainer就像

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>

)

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>

)