我正在尝试优化我的通用反应应用程序。似乎 bundle.js 在服务器端渲染重置整个 DOM 后读取。
我的理解是 React 客户端 javascript 不会重置整个 DOM,而是计算差异并在现有 DOM 上附加额外的 DOM 和事件。
我的 bundle.js 是 1.3 MB,这绝对是渲染缓慢的原因,但我没想到会重新渲染整个 DOM。
我的问题是通用渲染的预期行为吗?以及如何不重置所有 DOM?
服务器/index.js
const store = configureStore()
//****************
// App Setting
//****************
debug("Setting Application...")
const app = new Express()
app.use('/assets', Express.static('./assets'))
app.use('/build', Express.static('./build'))
app.get('*', (req, res) => {
const history = createHistory(req.originalUrl)
match({history, routes: createRoutes(store), location: req.originalUrl}, (error, redirectLocation, renderProps)=>{
const routes = createRoutes(store)
const components = (
<Provider store={store} key="provider">
<RouterContext {...renderProps} />
</Provider>
)
// React Dom Server Side Rendering
const app = ReactDOM.renderToStaticMarkup(<HTML components={components} store={store}/>)
// Response 200
res.status(200)
// Send response HTML
res.send(`<!doctype html>\n ${app}`)
})
})
app.listen(7777, () => debug('Server running on localhost:7777'))
客户端/index.js
let store
if (window.__REDUX_STORE__) {
store = configureStore(window.__REDUX_STORE__)
} else {
store = configureStore()
}
store.dispatch(fetchCurrentUserRequest())
render(
<Provider store={store}>
<AppRouter />
</Provider>,
document.querySelector('#content')
);
HTML.jsx
class HTML extends Component {
render(){
const { components, store } = this.props;
const content = components ? ReactDOM.renderToString(components): '';
return (
<html>
<head>
<link rel="stylesheet" href="build/style.css" />
</head>
<body>
<style>
* {
margin: 0;
padding: 0;
}
</style>
<div id="content" dangerouslySetInnerHTML={{__html: content}}/>
<script dangerouslySetInnerHTML={{__html: `window.__REDUX_STORE__=${serialize(store.getState())};`}} charSet="UTF-8"/>
<script src="build/bundle.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDnd7VpVekR7d09azP_RQ5Bb_bQHKMkSVo&libraries=places"></script>
</body>
</html>
)
}
}
export default HTML