【问题标题】:Use hydrate() with async. components将 hydrate() 与异步一起使用。成分
【发布时间】:2018-07-03 18:58:11
【问题描述】:

我正在开发的应用程序基于 React Fiber 和 React Router V3。

尝试使用hydrate() 而不是render()async components 我遇到了以下问题:从SSR 返回的HTML 与客户端不同。

因此,React 重新挂载整个 DOM 并抛出以下警告:Did not expect server HTML to contain...

React Training 也不提供解决方案:Code-splitting + server rendering

有什么办法可以实现吗?

更新:

简单示例

(伪代码)

App.js:

export default () => <div>Lorem Ipsum</div>;

client.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')
  );
});

server.js

match({routes: createRoutes(store), location: req.url},
  (err, redirectLocation, renderProps) => {
  const content = renderToString(<RouterContext {...renderProps}/>);
  // send content to client
});

【问题讨论】:

标签: javascript reactjs webpack react-router react-fiber


【解决方案1】:

我对该问题进行了更深入的调查并找到了解决方案。 为了实现 DOM 水合,以下几点应该是记账:

  1. 我在上面的例子中 client.js 我调用了 createRoutes(store) 两次。这是多余的,因为renderProps 已经为&lt;Route /&gt; 组件准备了routes 属性。由于这个错误,onEnter 被调用了两次,所以数据也被执行了两次。

  2. 为避免在服务器端和客户端端的 HTML 不匹配,onEnter 中的数据提取不应在第一个客户端呈现时调用。

  3. match 函数等待getComponent 回调在渲染之前执行。所以主要问题是错误的,因为这个功能是开箱即用的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 2019-11-10
    • 2012-09-02
    • 2018-04-16
    相关资源
    最近更新 更多