React服务端渲染(总结)(2)

8. 前端的react-router路由与node端路由如何配合?node如何知道该路由是渲染哪个数据呢?答:前端是以前的react-router配置,node端是react-router的match/RouterContext// 共享文件routes.js

const routes = ( <Route path="https://www.jb51.net/" component={ IComponent } > <Route path="/todo" component={ AComponent }> </Route> </Route> ) // 前端入口文件client.js render( <Router routes={ routes } history={ browserHistory } />, ele ) // node端入口文件server.js let app = express(); app.get('/todo', (req, res) => { match({ routes: routes, location: req.url }, async (err, redirect, props) => { // match会帮我们找到要渲染的组件链,注:上面一行使用了async语法,因此可以在render之前使用await运行拉取数据的代码 let html = renderToString(<RouterContext {...props} />) res.send( indexPage(html) ) } }) // node端返回 let indexPage = (html)=>{ return ` <!doctype html> <html lang="utf-8"> <head> <script> </script> </head> <body> <section >${html}</section> </body> <script src="https://www.jb51.net/static/vendor.js"></script> <script src="https://www.jb51.net/static/client.bundle.js"></script> </html> }

9. client.js中是否还能继续使用webpack的require.ensure ? 答:可以。但闪白明显,且node端返回html后会有报错,在加载脚本后该错误能忽略。 

10. 若我使用的是mobx,该如何实例化store ? 答:每一个node请求,都应该返回一个新的独立的store实例,而不是每个node请求共用一个store实例(笔者易犯)。

React服务端渲染(总结)

        

本demo地址( 前端库React+mobx+ReactRouter ):https://github.com/Penggggg/react-ssr

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wyfjgs.html