在我的反应SSR项目中实现异步路由(我使用loadable-components)之后。我发现staticContext
不起作用。如果我使用静态路由组件而不是异步组件,staticContext
将按预期工作。有什么建议吗?
这是我的NotFound
页面:
import React from 'react';
import Helmet from 'react-helmet';
import styles from './styles.scss';
type Props = { staticContext: Object };
export default ({ staticContext }: Props) => {
// I assing the 404 status here
if (staticContext) staticContext.status = '404';
return (
<div className={styles.NotFound}>
<Helmet title="Oops" />
<p>Oops, Page was not found!</p>
</div>
);
};
然后我从server.js
:
...
const staticContext = {};
const AppComponent = (
<Provider store={store}>
{/* Setup React-Router server-side rendering */}
<StaticRouter location={req.url} context={staticContext}>
{renderRoutes(routes)}
</StaticRouter>
</Provider>
);
if (staticContext.url) {
res.status(301).setHeader('Location', staticContext.url);
res.end();
return;
}
// Extract loadable state from application tree (loadable-components setup)
getLoadableState(AppComponent).then(loadableState => {
const head = Helmet.renderStatic();
const assets = webpackIsomorphicTools.assets();
const htmlContent = renderToString(AppComponent);
const initialState = store.getState();
const loadableStateTag = loadableState.getScriptTag();
// I can't get the "404" error
const status = staticContext.status === '404' ? 404 : 200;
...
反应:16.2.0 react-router:4.2.2 节点:9.5.0