我正在尝试使用 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/