将React-Router用于布局页面或每页面多个组件

我正在将React Router添加到现有项目中。

目前,将模型传递到根组件中,该组件包含用于子导航的导航组件和主要组件。

我发现的React Router的示例只有一个子组件,在不重复两个子组件的情况下改变两个子组件的最佳方法是什么?

老丝小小2020/04/03 11:37:59

2019年+

The simple and clean way to do it and avoid abusive re-rendering is (tested on react router v5, need to be confirmed on react router v4):

       <Switch>
         <Route exact path={["/route1/:id/:token", "/"]}>
          <Layout1>
            <Route path="/route1/:id/:token" component={SetPassword} />
            <Route exact path="/" component={SignIn} />
          </Layout1>
        </Route>
        <Route path={["/route2"]}>
          <Layout2>
            <Route path="/route2" component={Home} />
          </Layout2>
        </Route>
      </Switch>

which can be refactored to:

const routes = [
  {
    layout:Layout1,
    subRoutes:[
      {
        path:"/route1/:id/:token",
        component:SetPassword
      },
      {
        exact:true,
        path:"/",
        component:SignIn
      },
    ]
  },
  {
    layout:Layout2,
    subRoutes:[
      {
        path:"/route2",
        component:Home
      },
    ]
  }
];

with:

      <Switch>
        {routes.map((route,i)=>
          <Route key={i} exact={route.subRoutes.some(r=>r.exact)} path={route.subRoutes.map(r=>r.path)}>
            <route.layout>
              {route.subRoutes.map((subRoute,i)=>
                <Route key={i} {...subRoute} />
              )}
            </route.layout>
          </Route>
        )}
      </Switch>
西里Near2020/04/03 11:37:59

该组件可以是返回JSX的函数。

  <Route>
    <Route path="/" component={App}>
      <IndexRoute component={Home} />
      <Route path="Invite" component={()=>(<div><Home/><Invite/></div>)} />
    </Route>
  </Route>