React-Router忽略服务器上的嵌套路由

时间:2017-01-26 01:28:19

标签: javascript reactjs express react-router

我正在尝试使用Express.js在服务器端呈现React应用程序。但是,似乎我的一些路线被忽略了,我不知道为什么。

我的server.js

app.get('*', (req, res) => {
        console.log(routes);

  match(
    { routes: routes, location: req.url },
    (err, redirectLocation, renderProps) => {
      if (err) {
        return res.status(500).send(err.message);
      }
      if (redirectLocation) {
        return res.redirect(302, redirectLocation.pathname + redirectLocation.search);
      }
      let markup;
      if (renderProps) {
        var InitialComponent = (
          <Provider store={store}>
              <RouterContext {...renderProps} />
          </Provider>
        );
        markup = renderToString(InitialComponent);
      } else {
        markup = renderToString(<NotFoundPage/>);
        res.status(404);
      }
      return res.render('index', { markup });
    }
  );
});

Routes.js

export let routes = (

  <Route path="/" component={TransitionContainer}>
      <IndexRoute component={Home}/>
      <Route path="home" component={Home}/>
      <Route path="bom/:bomID/" component={BOM}/>
        <IndexRoute component={BomItemsGrid}/>
        <Route path="grid" component={BomItemsGrid}/>
        <Route path="table" component={BomItemsTable}/>
      <Route path="*" component={NotFoundPage}/>
    </Route>


)

当我导航到/bom/6/table时,我会得到以下

的React树
Provider
  Router
    RouterContext
      TransitionContainer
        NotFoundPage

由于某种原因,它会跳过BOM路由中定义的/bom/:bomID/组件,只会呈现NotFoundPage

为什么match()找不到路线,即使它被定义了?

1 个答案:

答案 0 :(得分:1)

哦,我错过了。您没有关闭BOM路线。这样:

<Route path="bom/:bomID/" component={BOM}/>

应该是:

<Route path="bom/:bomID/" component={BOM}> //<--- notice: No slash
  <IndexRoute component={BomItemsGrid}/>
  <Route path="grid" component={BomItemsGrid}/>
  <Route path="table" component={BomItemsTable}/>
</Route> //<--- add this