服务器渲染react-router v4 passthrough如果404

在react-router v3中,我们可以知道服务器端渲染何时与当前url不匹配。 这允许我将请求传递给我的express.static中间件,而不是发送呈现的应用程序。

在反应路由器v4中,我们必须使用

  const htmlData = renderToString( <StaticRouter location={req.url} context={context} > <App/> </StaticRouter> ); 

以便在服务器端渲染。 但是,它会自动将所有内容redirect到/ 。 为什么这种行为甚至存在? 难道我们不能像我们所期望的那样错误地失败吗?

我怎么能知道没有匹配的东西,我可以打电话给next() ,让另一个快递的路线做这个工作?

这是我想要使用的整个function:

 app.get('*', (req, res, next) => { const context = {}; const htmlData = renderToString( <StaticRouter location={req.url} context={context} > <App/> </StaticRouter> ); console.log(JSON.stringify(context, null, 4)); // empty object if (context.url) { // <------------------------ Doesn't work (taken from example and thought it would contain the unmatched url) winston.info(`Passing ${req.url} along`); next(); // <--------------- Never called even if no route matches. } else { res.send(pageContent.replace('<div id="main"></div>', `<div id="main">${htmlData}</div>`)); } }); 

我尝试了基于这个的东西,但是/ / // somewhere else是如此精确,我根本无法理解它。

这是我的最后一次尝试,以防万一。 这是我计划定义所有RouteRouter.jsx文件。

 import React from 'react'; import PropTypes from 'prop-types'; import { BrowserRouter, Route, } from 'react-router-dom'; import App from './components/App.jsx'; export const Status = ({ code, children }) => ( <Route render={({ staticContext }) => { if (staticContext) { staticContext.status = code; } return children; }}/> ); Status.propTypes = { code : PropTypes.number.isRequired, children : PropTypes.node.isRequired, }; export const NotFound = () => ( <Status code={404}> <div> <h1>Sorry, can't find that.</h1> </div> </Status> ); class Router extends React.Component { render() { return ( <BrowserRouter> <div> <Route exact path="/" component={App}/> <Route component={NotFound}/> </div> </BrowserRouter> ); } } export default Router; 

(我知道这是没有任何意义的,因为StaticRouter直接使用App而不关心Router.jsx但是我在App内部没有任何Route ,所以我不知道该怎么做。

您应该将NotFoundPage组件路由逻辑放入您的App.jsx文件中,而不是您根本不使用的Route.jsx。

 <Switch> <Route exact path="/" component={AppRootComponent}/> <Route component={NotFound}/> </Switch> 

除此之外,本教程代码是使用react路由器v4进行服务器端渲染的一个很好的参考。