【问题标题】:React-Router ignoring nested routes on serverReact-Router 忽略服务器上的嵌套路由
【发布时间】:2017-01-26 01:28:18
【问题描述】:

我正在尝试使用 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/:bomID/ 路由中定义的BOM 组件,只呈现NotFoundPage

为什么match()虽然定义了路由却找不到?

【问题讨论】:

  • 将路由从path="bom/:bomID/" 更改为path="bom/:bomID" 是否有效?我想知道额外的斜线是否会影响路由。
  • 刚试了一下,没有变化@KeithA

标签: javascript reactjs express react-router


【解决方案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

【讨论】:

  • 别这样。它发生在我们所有人身上。我有几次类似的错误。至少这是一个简单的小错误。它可能更难找到。
  • 是的。知道为什么我现在会在客户端收到像Uncaught Error: Unable to find element with ID 13. 这样的错误吗?如果我加载不同的页面然后导航到该路线,它工作正常,但如果我直接加载该路线,则会出现此错误。 @KeithA
  • 根据上面的代码我没有。调试器会抛出文件和行号吗?
  • 它源自ReactDOMComponent.receiveComponent (ReactDOMComponent.js:710),但堆栈跟踪中没有我的任何文件。@KeithA 也许我们应该把它交给 PM?用 SO 甚至可能吗?
猜你喜欢
  • 2019-12-25
  • 2016-07-30
  • 1970-01-01
  • 1970-01-01
  • 2019-11-04
  • 1970-01-01
  • 2015-02-21
  • 2016-05-03
  • 2017-02-03
相关资源
最近更新 更多