Build yourself react-ssr server side rendering architecture project

Recently I toss the next React to build the project ssr, tossing once before without much progress. The re-start of the project to build react architecture. Project Source: https://github.com/rt-zhangxuefei/react-ssr-template

Special thanks to: curriculum Delllee Mu class network . Here I used the saga instead of thunk, middle also encountered some pit, an intermediate layer agent uses the http-proxy-middleware. Article I set up recording some of the problems encountered in the process:

 

 

ssr process

1) to access the first screen (any url you first open the browser), the request reaches the server node

2) node service matching index.js in the routing table (routte url to access the directory based on)

3) inside the matching routing calls component loadData (their definition, used to obtain the data), the data acquisition components need only add a loadData method, where a plurality of routes may be matched, so there will be a plurality of loadData method, and these methods are asynchronous (sagas).

4) After all the asynchronous operation is complete, rendering the method call renderToString string html

5) express service to send html string to the browser (containing data) and has rendered good dom string

6) browser to get html string parsing display web content (ttfp)

7) browser requests a server based script src tag inside the address, download a client react js file

8) resolve js, react execution, it took over control of the entire page and interactive rendering

9) End

 

Project structure shown in Figure

Project Description

Analog own several interfaces (login, login judge, get a list of articles, comments list), in order to view comments after logging

Support for less, css module

What is water and dehydration

服务器端通过路由匹配出的组件的loadData方法(sagas)填充store,通过html字符串里面注入script标签引入变量的方式把store传给了浏览器,这个就是脱水。浏览器加载了包含reactjs的代码以后,把服务器注入过来的js对象的数据作为默认state传入createStore方法完成脱水过程。

服务器端渲染时react-router使用StaticRouter无状态路由

这里有个很重要的属性context,如下:

这个context参数会贯穿到浏览器和服务器端,成为一个数据交互的桥梁。比如判断前端路由重定向,404跳转等都是通过context作为判断来实现的。

css渲染

在具有样式的组件需要通过生命周期钩子注入css,让服务器端获取到并且渲染出来,这里就是一个应用(context作为数据桥梁)

组件的loadData(方法名称自己定义)

sagas就是store目录下的sagas

node作为中间层

所有的ajax请求都是通过node作为中间层来转发,这里使用了

http-proxy-middleware来实现,凡是url里面带有api的都进行转发。这样就会导致另外一个问题出来,那就是这个转发是针对浏览器的ajax请求。服务器端也会发同样的请求给后台api接口,差别只是url地址带没带host。

axios对象的createInstance方法

服务器端使用的axios实例和浏览器端使用的axios实例不一样,作为参数传递给sagas,这里需要注意传参的方式:

服务器端使用:

客户端使用:

之所以能够这样做是因为watch sagas都是在浏览器端调用的(比如通过生命周期钩子,或者点击事件等),而loadData是服务器端调用获取数据用来填充store的。

造轮子?

虽然有了next.js,但有时自己造轮子有时是需要的。当然next.js是非常受欢迎的,值得用来开发实际的项目

结尾

再次感谢DellLee老师的课程。花了2周的时间,完成了一个react-ssr项目架构,项目里面还有2个未解决的问题,一个是css在服务器和客户端都渲染了一次,另外一个就是code splitting或按需加载的问题。希望在后续的学习过程中能够解决遗留的问题。如果你解决,请留言告诉我!

 

作者: 张雪飞
出处: https://zhangxuefei.site/p/2166
版权说明:欢迎转载,但必须注明出处,并在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

Guess you like

Origin www.cnblogs.com/mszhangxuefei/p/10966134.html