我正在开发的应用程序基于 React Fiber 和 React Router V3。
尝试使用异步组件hydrate()
而不是异步组件时,我遇到了以下问题:从 SSR 返回的 HTML 与客户端不同。render()
结果,React 重新挂载了整个 DOM 并抛出以下警告:Did not expect server HTML to contain...
.
React Training 也不提供解决方案:代码拆分 + 服务器渲染
有什么解决方案可以实现这一目标吗?
更新:
简单示例
(伪代码)
应用程序.js:
export default () => <div>Lorem Ipsum</div>;
客户端.js:
const createRoutes = store => ({
path: '/',
getComponent(nextState, cb) {
require('./App'); // some async require
},
onEnter: (nextState, replace, cb) => {
store.dispatch(fetchData())
.then(() => cb())
.catch(cb);
}
});
match({history, routes: createRoutes(store)},
(error, redirectLocation, renderProps) => {
hydrate(
<Router history={history} routes={createRoutes(store)} />,
document.getElementById('app')
);
});
服务器.js
match({routes: createRoutes(store), location: req.url},
(err, redirectLocation, renderProps) => {
const content = renderToString(<RouterContext {...renderProps}/>);
// send content to client
});