In response-router v3, we could know when the server-side rendering did not match the current URL. This allowed me to submit a request for my middleware express.staticinstead of sending the displayed application.
In response-router v4 we should use
const htmlData = renderToString(
<StaticRouter
location={req.url}
context={context}
>
<App/>
</StaticRouter>
);
for server side rendering. However, it automatically redirects everything to /. Why does this behavior exist? Could we just make a mistake, how do we expect him to fail helplessly?
How could I know that nothing was agreed so that I could call next(), and other express routes did the job?
Here is the whole function that I would like to use:
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));
if (context.url) {
winston.info(`Passing ${req.url} along`);
next();
} else {
res.send(pageContent.replace('<div id="main"></div>',
`<div id="main">${htmlData}</div>`));
}
});
this, // somewhere else , .
, . Router.jsx, Route s.
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, Route App, , .