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

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

路由.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/:bomID/ 路由中定义的 BOM 组件,只渲染 NotFoundPage

为什么即使定义了路由,match()也找不到路由?

最佳答案

哦,我错过了。您没有关闭 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

关于javascript - React-Router 忽略服务器上的嵌套路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41864589/

相关文章:

javascript - 只给我点击样式的元素

javascript - 如何根据 bool 值自动移动 JSON 数据

javascript - 在映射函数中响应条件语句

mongodb - Graphql 创建两个查询之间的关系。错误无法在初始化之前访问

session - Node.js - 中间件中的 res.redirect 问题

javascript - 如何最好地将参数标记为已忽略

javascript - jQuery 中操作一组 id 的函数

javascript - Ember.js ArrayController 错误

reactjs - Fluent UI DetailsList - 有没有办法向每一列添加过滤器

javascript - 如何生成 404 错误而不是强制转换错误