router4.0能不能像router3.0那样嵌套配置?



  • react-router3.0一般被嵌套用法。

    const routeConfig = [
      { path: '/',
        component: App,
        indexRoute: { component: Dashboard },
        childRoutes: [
          { path: 'about', component: About },
          { path: 'inbox',
            component: Inbox,
            childRoutes: [
              { path: '/messages/:id', component: Message },
              { path: 'messages/:id',
                onEnter: function (nextState, replaceState) {
                  replaceState(null, '/messages/' + nextState.params.id)
                }
              }
            ]
          }
        ]
      }
    ]
    React.render(<Router routes={routeConfig} />, document.body)
    

    这样的全局统一配置我觉得易于管理和维护,我很喜欢用它
    那么4.0能不能像这样配置呢?
    官方是提供了一个 route-config 的配置,但我感觉它是不方便的。每个页面分发路由的地方都要去循环调用一下循环方法。如:

    import React from "react";
    import { BrowserRouter as Router, Route, Link } from "react-router-dom";
    
    ////////////////////////////////////////////////////////////
    // first our route components
    const Main = () => <h2>Main</h2>;
    
    const Sandwiches = () => <h2>Sandwiches</h2>;
    
    const Tacos = ({ routes }) => (
      <div>
        <h2>Tacos</h2>
        <ul>
          <li>
            <Link to="/tacos/bus">Bus</Link>
          </li>
          <li>
            <Link to="/tacos/cart">Cart</Link>
          </li>
        </ul>
    // **************************** here ******************************
        {routes.map((route, i) => <RouteWithSubRoutes key={i} {...route} />)}
      </div>
    );
    
    const Bus = () => <h3>Bus</h3>;
    const Cart = () => <h3>Cart</h3>;
    
    ////////////////////////////////////////////////////////////
    const routes = [
      {
        path: "/sandwiches",
        component: Sandwiches
      },
      {
        path: "/tacos",
        component: Tacos,
        routes: [
          {
            path: "/tacos/bus",
            component: Bus
          },
          {
            path: "/tacos/cart",
            component: Cart
          }
        ]
      }
    ];
    
    const RouteWithSubRoutes = route => (
      <Route
        path={route.path}
        render={props => (
          // // here
          <route.component {...props} routes={route.routes} />
        )}
      />
    );
    
    const RouteConfigExample = () => (
      <Router>
        <div>
          <ul>
            <li>
              <Link to="/tacos">Tacos</Link>
            </li>
            <li>
              <Link to="/sandwiches">Sandwiches</Link>
            </li>
          </ul>
    // **************************** here ******************************
          {routes.map((route, i) => <RouteWithSubRoutes key={i} {...route} />)}
        </div>
      </Router>
    );
    export default RouteConfigExample;
    

    这里出现两段相同的代码 ** here ** 处,是否有更好的办法来优化它?
    期待oldSong回复,谢谢


Log in to reply
 

Looks like your connection to 新前端社区 was lost, please wait while we try to reconnect.