Home Web Front-end JS Tutorial How to use React server-side rendering

How to use React server-side rendering

May 31, 2018 am 09:48 AM
react server rendering

This time I will show you how to use React server-side rendering, and what are the precautions for using React server-side rendering. The following is a practical case, let's take a look.

React provides two methods renderToString and renderToStaticMarkup to output the component (Virtual DOM) into HTML

String, which is the basis of React server-side rendering, which removes the server-side The dependence on the browser environment makes server-side rendering an attractive thing.

In addition to solving the dependence on the browser environment, server-side rendering also needs to solve two problems:

  1. The front and back ends can share code

  2. Front-end and back-end routing can be processed uniformly

The React ecosystem provides many options. Here we choose Redux and react-router for illustration.

Redux

Redux provides a set of one-way data flow similar to Flux. The entire application only maintains one Store and is functional-oriented. Features make it friendly for server-side rendering support.

2 minutes to learn how Redux works

About Store:

  1. The entire application only A unique Store

  2. The corresponding state tree (State) of the Store is generated by calling a reducer function (root reducer)

  3. on the state tree Each field can be further generated by different reducer functions

  4. Store contains several methods such as dispatch and getState to process the data stream

  5. Store's state tree can only be triggered by dispatch(action) to change

Redux's data flow:

  1. action is a { type , payload } object

  2. reducer function is triggered by store.dispatch(action)

  3. reducer function accepts (state, action) two parameters , return a new state

  4. The reducer function determines action.type and then processes the corresponding action.payload data to

    update the state tree

So for the entire application, one Store corresponds to one UI snapshot. Server-side rendering is simplified to initializing the Store on the server side, passing the Store to the root component of the application, and calling renderToString on the root component to render the entire application. Output as HTML containing initialization data.

react-router

react-router matches different routing decisions in a declarative way to display different components on the page, and The routing information is passed to the component through props, so as long as the routing changes, the props will change, triggering the component to re-render.

Suppose there is a very simple application with only two pages, a list page /list and a details page /item/:id. Click an item on the list to enter the details page.

You can define routes like this

, ./routes.js

Starting from here, we use this very simple application to explain the front-end and back-end aspects of implementing server-side rendering. Some details.

ReducerStore is generated by reducer, so reducer actually reflects the state tree structure of Store

. /reducers/index.js

import listReducer from './list';
import itemReducer from './item';
export default function rootReducer(state = {}, action) {
 return {
  list: listReducer(state.list, action),
  item: itemReducer(state.item, action)
 };
}
Copy after login

The state parameter of rootReducer is the state tree of the entire Store. Each field under the state tree can also have its own reducer, so listReducer and itemReducer are introduced here, as you can see The state parameters of these two reducers are just the corresponding list and item fields on the entire state tree.

Specific to ./reducers/list.js

const initialState = [];
export default function listReducer(state = initialState, action) {
 switch(action.type) {
 case 'FETCH_LIST_SUCCESS': return [...action.payload];
 default: return state;
 }
}
Copy after login

list is a simple array containing items, which may be similar to this structure: [{ id: 0, name: 'first item'} , {id: 1, name: 'second item'}], obtained from action.payload of 'FETCH_LIST_SUCCESS'.

Then ./reducers/item.js to process the obtained item data

const initialState = {};
export default function listReducer(state = initialState, action) {
 switch(action.type) {
 case 'FETCH_ITEM_SUCCESS': return [...action.payload];
 default: return state;
 }
}
Copy after login

Action

对应的应该要有两个 action 来获取 list 和 item,触发 reducer 更改 Store,这里我们定义 fetchList 和 fetchItem 两个 action。

./actions/index.js

import fetch from 'isomorphic-fetch';
export function fetchList() {
 return (dispatch) => {
  return fetch('/api/list')
    .then(res => res.json())
    .then(json => dispatch({ type: 'FETCH_LIST_SUCCESS', payload: json }));
 }
}
export function fetchItem(id) {
 return (dispatch) => {
  if (!id) return Promise.resolve();
  return fetch(`/api/item/${id}`)
    .then(res => res.json())
    .then(json => dispatch({ type: 'FETCH_ITEM_SUCCESS', payload: json }));
 }
}
Copy after login

isomorphic-fetch 是一个前后端通用的 Ajax 实现,前后端要共享代码这点很重要。

另外因为涉及到异步请求,这里的 action 用到了 thunk,也就是函数,redux 通过 thunk-middleware 来处理这类 action,把函数当作普通的 action dispatch 就好了,比如 dispatch(fetchList())

Store

我们用一个独立的 ./store.js,配置(比如 Apply Middleware)生成 Store

import { createStore } from 'redux';
import rootReducer from './reducers';
// Apply middleware here
// ...
export default function configureStore(initialState) {
 const store = createStore(rootReducer, initialState);
 return store;
}
Copy after login

react-redux

接下来实现 组件,然后把 redux 和 react 组件关联起来,具体细节参见 react-redux

./app.js

import React from 'react';
import { render } from 'react-dom';
import { Router } from 'react-router';
import createBrowserHistory from 'history/lib/createBrowserHistory';
import { Provider } from 'react-redux';
import routes from './routes';
import configureStore from './store';
// `INITIAL_STATE` 来自服务器端渲染,下一部分细说
const initialState = window.INITIAL_STATE;
const store = configureStore(initialState);
const Root = (props) => {
 return (
  <p>
   <Provider store={store}>
    <Router history={createBrowserHistory()}>
     {routes}
    </Router>
   </Provider>
  </p>
 );
}
render(<Root />, document.getElementById('root'));
Copy after login

至此,客户端部分结束。

Server Rendering

接下来的服务器端就比较简单了,获取数据可以调用 action,routes 在服务器端的处理参考 react-router server rendering,在服务器端用一个 match 方法将拿到的 request url 匹配到我们之前定义的 routes,解析成和客户端一致的 props 对象传递给组件。

./server.js

import express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { RoutingContext, match } from 'react-router';
import { Provider } from 'react-redux';
import routes from './routes';
import configureStore from './store';
const app = express();
function renderFullPage(html, initialState) {
 return `
  <!DOCTYPE html>
  <html lang="en">
  <head>
   <meta charset="UTF-8">
  </head>
  <body>
   <p id="root">
    <p>
     ${html}
    </p>
   </p>
   <script>
    window.INITIAL_STATE = ${JSON.stringify(initialState)};
   </script>
   <script src="/static/bundle.js"></script>
  </body>
  </html>
 `;
}
app.use((req, res) => {
 match({ routes, location: req.url }, (err, redirectLocation, renderProps) => {
  if (err) {
   res.status(500).end(`Internal Server Error ${err}`);
  } else if (redirectLocation) {
   res.redirect(redirectLocation.pathname + redirectLocation.search);
  } else if (renderProps) {
   const store = configureStore();
   const state = store.getState();
   Promise.all([
    store.dispatch(fetchList()),
    store.dispatch(fetchItem(renderProps.params.id))
   ])
   .then(() => {
    const html = renderToString(
     <Provider store={store}>
      <RoutingContext {...renderProps} />
     </Provider>
    );
    res.end(renderFullPage(html, store.getState()));
   });
  } else {
   res.status(404).end('Not found');
  }
 });
});
Copy after login

服务器端渲染部分可以直接通过共用客户端 store.dispatch(action) 来统一获取 Store 数据。另外注意 renderFullPage 生成的页面 HTML 在 React 组件 mount 的部分(

),前后端的 HTML 结构应该是一致的。然后要把 store 的状态树写入一个全局变量(INITIAL_STATE),这样客户端初始化 render 的时候能够校验服务器生成的 HTML 结构,并且同步到初始化状态,然后整个页面被客户端接管。

最后关于页面内链接跳转如何处理?

react-router 提供了一个 组件用来替代 标签,它负责管理浏览器 history,从而不是每次点击链接都去请求服务器,然后可以通过绑定 onClick 事件来作其他处理。

比如在 /list 页面,对于每一个 item 都会用 绑定一个 route url:/item/:id,并且绑定 onClick 去触发 dispatch(fetchItem(id)) 获取数据,显示详情页内容。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

怎样使用JS实现计算圆周率到小数点后100位

怎样使用vue axios 给生产与发布环境配置接口地址

The above is the detailed content of How to use React server-side rendering. 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 configure Dnsmasq as a DHCP relay server How to configure Dnsmasq as a DHCP relay server Mar 21, 2024 am 08:50 AM

The role of a DHCP relay is to forward received DHCP packets to another DHCP server on the network, even if the two servers are on different subnets. By using a DHCP relay, you can deploy a centralized DHCP server in the network center and use it to dynamically assign IP addresses to all network subnets/VLANs. Dnsmasq is a commonly used DNS and DHCP protocol server that can be configured as a DHCP relay server to help manage dynamic host configurations in the network. In this article, we will show you how to configure dnsmasq as a DHCP relay server. Content Topics: Network Topology Configuring Static IP Addresses on a DHCP Relay D on a Centralized DHCP Server

Best Practice Guide for Building IP Proxy Servers with PHP Best Practice Guide for Building IP Proxy Servers with PHP Mar 11, 2024 am 08:36 AM

In network data transmission, IP proxy servers play an important role, helping users hide their real IP addresses, protect privacy, and improve access speeds. In this article, we will introduce the best practice guide on how to build an IP proxy server with PHP and provide specific code examples. What is an IP proxy server? An IP proxy server is an intermediate server located between the user and the target server. It acts as a transfer station between the user and the target server, forwarding the user's requests and responses. By using an IP proxy server

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.

What should I do if I can't enter the game when the epic server is offline? Solution to why Epic cannot enter the game offline What should I do if I can't enter the game when the epic server is offline? Solution to why Epic cannot enter the game offline Mar 13, 2024 pm 04:40 PM

What should I do if I can’t enter the game when the epic server is offline? This problem must have been encountered by many friends. When this prompt appears, the genuine game cannot be started. This problem is usually caused by interference from the network and security software. So how should it be solved? The editor of this issue will explain I would like to share the solution with you, I hope today’s software tutorial can help you solve the problem. What to do if the epic server cannot enter the game when it is offline: 1. It may be interfered by security software. Close the game platform and security software and then restart. 2. The second is that the network fluctuates too much. Try restarting the router to see if it works. If the conditions are OK, you can try to use the 5g mobile network to operate. 3. Then there may be more

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.

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.

How to install PHP FFmpeg extension on server? How to install PHP FFmpeg extension on server? Mar 28, 2024 pm 02:39 PM

How to install PHPFFmpeg extension on server? Installing the PHPFFmpeg extension on the server can help us process audio and video files in PHP projects and implement functions such as encoding, decoding, editing, and processing of audio and video files. This article will introduce how to install the PHPFFmpeg extension on the server, as well as specific code examples. First, we need to ensure that PHP and FFmpeg are installed on the server. If FFmpeg is not installed, you can follow the steps below to install FFmpe

Detailed explanation of the advantages and utility of Golang server Detailed explanation of the advantages and utility of Golang server Mar 20, 2024 pm 01:51 PM

Golang is an open source programming language developed by Google. It is efficient, fast and powerful and is widely used in cloud computing, network programming, big data processing and other fields. As a strongly typed, static language, Golang has many advantages when building server-side applications. This article will analyze the advantages and utility of Golang server in detail, and illustrate its power through specific code examples. 1. The high-performance Golang compiler can compile the code into local code

See all articles