Home Web Front-end JS Tutorial React front-end and back-end isomorphic rendering sample code

React front-end and back-end isomorphic rendering sample code

Feb 12, 2018 am 09:10 AM
react rendering Example

Isomorphic rendering of front and rear ends: When the client requests a page containing React components, the server first responds and outputs the page, and the client and server have their first interaction. Then, if the process of loading components requires making an Ajax request to the server, the client and server interact again, which takes a relatively long time. Front-end and back-end isomorphic rendering can render all places and respond to the client in one go when the page is first loaded. This article mainly introduces you to the front-end and back-end isomorphic rendering of React. The editor thinks it is quite good. Now I will share it with you and give you a reference. Let’s follow the editor to take a look, I hope it can help everyone.

Implementation method: Ensure that the package management tool and module dependency are consistent

Package management tool-npm management ensures that both the front and back ends use the same one Compatibility package

Module dependency method-webpack ensures that both the front and back ends adopt the commonjs dependency method to ensure that the codes can depend on each other

How to render on the server side:
react family bucket: react, react-router, redux

react and reactDOM

The support provided by reactDOM here is reactDOM.render and reactDOM.renderToString function, which will generate the DOM structure in the browser, and the latter will generate the corresponding HTML string template on the server. React will add a data-react-checksum attribute to the generated DOM structure, which is a checksum of the adler32 algorithm to ensure the consistency of the two templates.

React front-end and back-end isomorphic rendering sample code

At the same time, the life cycle of react is also different during the front-end and back-end rendering processes. Front-end rendering components have a complete life cycle, while back-end rendering only has the life cycle of componentWillMount. This means that if we want to perform joint operation logic on the front and back ends, such as sending data requests, etc., we can place it in the life cycle of componentWillMount; if we want to handle the client logic separately, we can place it in other life cycles, such as componentDidMount.

react-router

react-router is a react routing-view control library that can write boundary declarative routing to control the rendering of different pages. react-router itself is a state machine. According to the configured routing rules and the input url path, the corresponding component is found and rendered through the match method.

React front-end and back-end isomorphic rendering sample code

This mechanism is connected to both the front-end and the back-end. For example, in the back-end, the following implementation form is used for rendering:


app.use(async (ctx, next) => { 
match({ 
location: ctx.originalUrl, 
routes 
}, callback) 
// 渲染完成之后,调用 callback 回调 
// 将 组件 renderToString 返回前端即可 
})
Copy after login

For the front end, the above logic is actually processed, but it is well encapsulated in the component. We only need to write declarative routing, and all this is Can happen automatically as the url changes.

redux

redux is react's data flow management library. Its support for server-side rendering is very simple, that is, a single store and state can be initialized. The backend will build a single store when rendering, and write the built initial state to the generated HTML string template in json format and through global variables.
By obtaining the initial state and generating a store that is exactly the same as the back-end after completion, the front-end can ensure the consistency of the front-end and back-end rendering data and ensure that the DOM structures generated by the front-end and back-end are consistent.

Optimization results:

The problem of low development efficiency: isomorphic applications only have one project and a set of technology stacks. As long as you have react development experience, you can Quickly invest in front-end and back-end development;
The problem of poor maintainability: Isomorphic applications can share a large amount of code, including tool methods, constants, page components and most of the logic of redux, etc., greatly improving reusability; First screen performance, SEO, etc.

Processing process:

The client makes a request-the server renders the component-returns to the client

1. Place the placeholder


<p id="root">@@@</p>
###
Copy after login

on the page that needs to be isomorphic (such as index.html). When the client makes the first request , the server renders the html content of the component and puts it at the @@@ position, and then the server renders a js code segment similar to this to finally render the component to the DOM. In other words, the renderApp method actually renders the component.

2. In order to directly call the renderApp method, the renderApp method must become a method under window


window.renderApp = function(){ReactDOM.render(...)}
Copy after login

3. The server takes out index.html and renders it. Extract the content of the placeholder, replace the placeholder, and respond to the client in one go

Case

File structure


##

browser.js(在这里把渲染组件的过程赋值给window.renderApp)

bundle.js(把browser.js内容bundle到这里)

Component.js(组件在这里定义)

express.js(服务端)

index.html(同构直出的页面)

package.json
Copy after login

index.html, go straight out of the page and put the placeholder


<!doctype html>
<html>
<head>
 <meta charset="UTF-8">
 <title>Untitled Document</title>
</head>
<body>

 <p id="root">@@@</p>
 <script src="bundle.js"></script>
 ###
</body>
</html>
Copy after login

Component.js, define the component here


var React = require(&#39;react&#39;);
var ReactDOM = require(&#39;react-dom&#39;);

var Component = React.createClass({
 clickHandler: function(){
  alert(this.props.msg)
 },

 render: function(){
  return React.createElement(&#39;button&#39;, {onClick: this.clickHandler}, this.props.msg)
 }

})

module.exports = Component;
Copy after login

browser.js, assign the component rendering process to the window object


var React = require(&#39;react&#39;);
var ReactDOM = require(&#39;react-dom&#39;);

var Component = React.createFactory(require(&#39;./Component&#39;));

window.renderApp = function(msg){
 ReactDOM.render(Component({msg: msg}), document.getElementById(&#39;root&#39;)); 
}
Copy after login

可以通过来触发组件的渲染。稍后,在服务端会把这段代码渲染出来。

express.js,服务端

以上,需要直出的页面有了占位符,定义了组件,并把渲染组件的过程赋值给了window对象,服务端现在要做的工作就是:生成组件的html和渲染组件的js,放到直出页面index.html的占位符位置。


var express = require(&#39;express&#39;);
var React = require(&#39;react&#39;);
var ReactDOMServer = require(&#39;react-dom/server&#39;);
var fs = require(&#39;fs&#39;);
var Component = React.createFactory(require(&#39;./Component&#39;));

//原先把文件读出来
var BUNDLE = fs.readFileSync(&#39;./bundle.js&#39;,{encoding:&#39;utf8&#39;});
var TEMPLATE = fs.readFileSync(&#39;./index.html&#39;,{encoding:&#39;utf8&#39;});

var app = express();

function home(req, res){
 var msg = req.params.msg || &#39;Hello&#39;;
 var comp = Component({msg: msg});

 //@@@占位符的地方放组件
 var page = TEMPLATE.replace(&#39;@@@&#39;, ReactDOMServer.renderToString(comp));

 //###占位符的地方放js
 page = page.replace(&#39;###&#39;, &#39;<script>renderApp("&#39;+msg+&#39;")</script>&#39;)
 res.send(page);
}

//路由
app.get(&#39;&#39;, home);
app.get(&#39;/bundle.js&#39;, function(req, res){
 res.send(BUNDLE);
})
app.get(&#39;/:msg&#39;, home);

app.listen(4000);
Copy after login

package.json中的配置


"scripts": {
"start": "watchify ./browser.js -o ./bundle.js"
},
Copy after login

启动方式
运行:npm start
运行:node express.js
浏览:localhost:4000

相关推荐:

实现react服务器渲染基础方法

React前后端同构防止重复渲染

React将组件渲染到指定DOM节点的方法详解

The above is the detailed content of React front-end and back-end isomorphic rendering sample code. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to render orthogonal top view in Kujiale_Tutorial on rendering orthogonal top view in Kujiale How to render orthogonal top view in Kujiale_Tutorial on rendering orthogonal top view in Kujiale Apr 02, 2024 pm 01:10 PM

1. First open the design plan to be rendered in Kujiale. 2. Then open top view rendering under the rendering menu. 3. Then click Orthogonal in the parameter settings in the top view rendering interface. 4. Finally, after adjusting the model angle, click Render Now to render the orthogonal top view.

Oracle DECODE function detailed explanation and usage examples Oracle DECODE function detailed explanation and usage examples Mar 08, 2024 pm 03:51 PM

The DECODE function in Oracle is a conditional expression that is often used to return different results based on different conditions in query statements. This article will introduce the syntax, usage and sample code of the DECODE function in detail. 1. DECODE function syntax DECODE(expr,search1,result1[,search2,result2,...,default]) expr: the expression or field to be compared. search1,

Go language indentation specifications and examples Go language indentation specifications and examples Mar 22, 2024 pm 09:33 PM

Indentation specifications and examples of Go language Go language is a programming language developed by Google. It is known for its concise and clear syntax, in which indentation specifications play a crucial role in the readability and beauty of the code. effect. This article will introduce the indentation specifications of the Go language and explain in detail through specific code examples. Indentation specifications In the Go language, tabs are used for indentation instead of spaces. Each level of indentation is one tab, usually set to a width of 4 spaces. Such specifications unify the coding style and enable teams to work together to compile

PHP, Vue and React: How to choose the most suitable front-end framework? PHP, Vue and React: How to choose the most suitable front-end framework? Mar 15, 2024 pm 05:48 PM

PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.

Introduction to Python functions: Usage and examples of isinstance function Introduction to Python functions: Usage and examples of isinstance function Nov 04, 2023 pm 03:15 PM

Introduction to Python functions: Usage and examples of the isinstance function Python is a powerful programming language that provides many built-in functions to make programming more convenient and efficient. One of the very useful built-in functions is the isinstance() function. This article will introduce the usage and examples of the isinstance function and provide specific code examples. The isinstance() function is used to determine whether an object is an instance of a specified class or type. The syntax of this function is as follows

Integration of Java framework and front-end React framework Integration of Java framework and front-end React framework Jun 01, 2024 pm 03:16 PM

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.

Introduction to Python functions: functions and examples of eval function Introduction to Python functions: functions and examples of eval function Nov 04, 2023 pm 12:24 PM

Introduction to Python functions: functions and examples of the eval function In Python programming, the eval function is a very useful function. The eval function can execute a string as program code, and its function is very powerful. In this article, we will introduce the detailed functions of the eval function, as well as some usage examples. 1. Function of eval function The function of eval function is very simple. It can execute a string as Python code. This means that we can convert a string

Application and example analysis of PHP dot operator Application and example analysis of PHP dot operator Mar 28, 2024 pm 12:06 PM

Application and example analysis of PHP dot operator In PHP, the dot operator (".") is an operator used to connect two strings. It is very commonly used and very flexible when concatenating strings. By using the dot operator, we can easily concatenate multiple strings to form a new string. The following will introduce the use of PHP dot operators through example analysis. 1. Basic usage First, let’s look at a basic usage example. Suppose there are two variables $str1 and $str2, which store two words respectively.

See all articles