Home > Web Front-end > JS Tutorial > body text

How to use React server-side rendering

php中世界最好的语言
Release: 2018-05-31 09:48:33
Original
1280 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!