How to use React server-side rendering efficiently
This time I will show you how to use React server-side rendering efficiently, and what are the precautions for using React server-side rendering. Here are practical cases, let’s take a look.
React provides two methods renderToString and renderToStaticMarkup to output the component (Virtual DOM) into HTML In addition to solving the dependence on the browser environment, server-side rendering also needs to solve two problems:- The front and back ends can share code
- Front-end and back-end routing can be processed uniformly
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:- The entire application only A unique Store
- The corresponding state tree (State) of the Store is generated by calling a reducer function (root reducer)
- on the state tree Each field can be further generated by different reducer functions
- Store contains several methods such as dispatch and getState to process the data stream
- Store's state tree can only be triggered by dispatch(action) to change
- action is a { type , payload } object
- reducer function is triggered by store.dispatch(action)
- reducer function accepts (state, action) two parameters , return a new state
- The reducer function determines action.type and then processes the corresponding action.payload data to
update the state tree
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 this1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
ReducerStore is generated by reducer, so reducer actually reflects the state tree structure of Store
. /reducers/index.js
1 2 3 4 5 6 7 8 |
|
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
1 2 3 4 5 6 7 |
|
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
1 2 3 4 5 6 7 |
|
Action
对应的应该要有两个 action 来获取 list 和 item,触发 reducer 更改 Store,这里我们定义 fetchList 和 fetchItem 两个 action。
./actions/index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
isomorphic-fetch 是一个前后端通用的 Ajax 实现,前后端要共享代码这点很重要。
另外因为涉及到异步请求,这里的 action 用到了 thunk,也就是函数,redux 通过 thunk-middleware 来处理这类 action,把函数当作普通的 action dispatch 就好了,比如 dispatch(fetchList())
Store
我们用一个独立的 ./store.js,配置(比如 Apply Middleware)生成 Store
1 2 3 4 5 6 7 8 |
|
react-redux
接下来实现 ,
./app.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
至此,客户端部分结束。
Server Rendering
接下来的服务器端就比较简单了,获取数据可以调用 action,routes 在服务器端的处理参考 react-router server rendering,在服务器端用一个 match 方法将拿到的 request url 匹配到我们之前定义的 routes,解析成和客户端一致的 props 对象传递给组件。
./server.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
|
服务器端渲染部分可以直接通过共用客户端 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中文网其它相关文章!
推荐阅读:
vue axios生产环境与发布环境配置不同接口地址步骤详解
The above is the detailed content of How to use React server-side rendering efficiently. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

Xiaomi car software provides remote car control functions, allowing users to remotely control the vehicle through mobile phones or computers, such as opening and closing the vehicle's doors and windows, starting the engine, controlling the vehicle's air conditioner and audio, etc. The following is the use and content of this software, let's learn about it together . Comprehensive list of Xiaomi Auto app functions and usage methods 1. The Xiaomi Auto app was launched on the Apple AppStore on March 25, and can now be downloaded from the app store on Android phones; Car purchase: Learn about the core highlights and technical parameters of Xiaomi Auto, and make an appointment for a test drive. Configure and order your Xiaomi car, and support online processing of car pickup to-do items. 3. Community: Understand Xiaomi Auto brand information, exchange car experience, and share wonderful car life; 4. Car control: The mobile phone is the remote control, remote control, real-time security, easy

Go language is a simple, efficient, and highly concurrency programming language. It is an open source language developed by Google. In the Go language, the use of spaces is very important, it can improve the readability and maintainability of the code. This article will introduce how to use spaces correctly in Go language and provide specific code examples. Why you need to use spaces correctly In the programming process, the use of spaces is very important for the readability and beauty of the code. Appropriate use of spaces can make code clearer and easier to read, thus reducing

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.

What are full-width characters? In computer encoding systems, double-width characters are a character encoding method that takes up two standard character positions. Correspondingly, the character encoding method that occupies a standard character position is called a half-width character. Full-width characters are usually used for input, display and printing of Chinese, Japanese, Korean and other Asian characters. In Chinese input methods and text editing, the usage scenarios of full-width characters and half-width characters are different. Use of full-width characters Chinese input method: In the Chinese input method, full-width characters are usually used to input Chinese characters, such as Chinese characters, symbols, etc.

According to news from this website on July 23, ASUS has launched a variety of server and workstation-level products powered by AMD EPYC 4004 series processors. Note from this site: AMD launched the AM5 platform and Zen4 architecture EPYC 4004 series processors in May, offering up to 16-core 3DV-Cache specifications. ASUSProER100AB6 server ASUSProER100AB6 is a 1U rack server product equipped with EPYC Xiaolong 4004 series processor, suitable for the needs of IDC and small and medium-sized enterprises. ASUSExpertCenterProET500AB6 workstation ASUSExpertCenterProET500AB6 is a
