服务器端渲染在客户端重新渲染

6
我正在尝试使用Django,Express,React和React Router Dom实现服务器端渲染。
server.js
const html = renderToString((
    <Provider store={store}>
      <StaticRouter basename={baseUrl} location={location} context={context}>
        <AppRoute />
      </StaticRouter>
    </Provider>
  ), null, 2);

  const preloadedState = store.getState();

  res.send(renderFullPage(html, preloadedState))

客户端的index.js

ReactDOM.render(
  <Provider store={store}>
    <Router>
      <AppRoute />
    </Router>
  </Provider>,
  document.getElementById('app')
);

"AppRoute使用RouteAsync作为客户端,使用RouteSync作为服务器。

AppRoute.js导入

"
import {App} from './RouteSync'
import {CollegeList} from './RouteSync'
import {CollegeDetail} from './RouteSync'

RouteAsync.js

export const App = asyncRoute(() => System.import('../app'));
export const CollegeList = asyncRoute(() => System.import('../apps/college/CollegeList'));
export const CollegeDetail = asyncRoute(() => System.import('../apps/college/CollegeDetail'));

RouteSync.js

export { default as App } from '../app'
export { default as CollegeList } from '../apps/college/CollegeList'
export { default as CollegeDetail } from '../apps/college/CollegeDetail'

webpack的NormalModuleReplacementPlugin插件将RouteSync更改为RouteAsync。
new webpack.NormalModuleReplacementPlugin(
      /\.\/RouteSync$/,
      './RouteAsync'
    ),

服务器渲染完成并发送给客户端。在客户端,当使用开发工具性能查看时,SSR客户端再次重新渲染整个页面。 开发工具“性能”图像显示客户端重新渲染前的空白页面 我希望React只是挂接事件监听器,而不是重新渲染页面。
有什么建议可以阻止客户端重新渲染。

2
你有没有找到解决办法?在我们的生产应用程序中,我在更新到react-router 4(react-router-dom)后遇到了这个问题。 - felguerez
从asyncRoute导入的组件会重新渲染,但从Sync方法加载的组件不会重新渲染。解决方案:
  1. 我选择了不必重新渲染的组件。
  2. 在RouteAsync.js文件中,这些组件被导入到RouteSync.js中。
因此,在客户端不会重新渲染所选组件。 这是我阅读后想出的唯一解决方案。
- Roshan Shrestha
在https://reacttraining.com/react-router/web/guides/code-splitting中的“代码分割+服务器渲染”主题 - Roshan Shrestha
1个回答

1
我也没有找到答案。所以我创建了自己的启动器。它使用react-router v4、redux和redux-saga。为了防止在客户端上第一次打开链接时重新渲染,使用hydrate方法。我根据官方文档和react-router v4和redux的建议创建了这个启动器。希望它能有所帮助。

https://github.com/gzoreslav/react-redux-saga-universal-application


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接