Last week, I used Next. Js to develop for a week. Here are some development and learning experiences.

A, getInitialProps

What is a getInitialProps

In next.js, we provide a static asynchronous method, getInitialProps, which can asynchronously get regular JS objects and bind them to props, so that we can get interface data on the service.

  static async getInitialProps({ req }) {
    console.log(req)
    return{}}Copy the code

If you look at the code above, you’ll see that there is also a REQ object that refers to the request object as a service, but as a separate front-end project that has no interaction with the server side. However, in traditional React projects, componetDidMounted is used to retrieve interface data. We can still use it in Next. Js, since this function only exists on the client side, continuing to use componetDidMounted may lose the soul of SSR applications.

Next.js + Mobx ?

If we were using Mobx for state management in our project, how to “dispatch” getInitialProps and inject this. Props, of course, is not possible because getInitialProps is a static method and cannot use this object. If you have to combine Next. Js with Mobx, you might not be able to use getInitialProps and use componetDidMounted, or you might be able to use only one page and one store.

How to configure next.js

Next. Js is a tool for react server rendering. By default, pages is used as the render route path. How do I do some configuration on next.js? There are two methods. Method 1: Configure the IP address in the root directory of next. Method 2: Customize a server.js.

next.config.js

Webpack can be configured using the BundleAnalyzerPlugin, for example

const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')... module.exports = BundleAnalyzerPlugin({ ... })Copy the code
server.js

Create the Next entry file server.js and implement the app.prepare method to do some pre-work. If the server uses Express, it can control the routing itself:

const app = next({ dev })
...
app.prepare()
  .then((a)= > {
    const server = express()
    server.get('/page/:id', (req, res) => {
          const page = '/pageXX'
          const params = { id: req.params.id }
          app.render(req, res, page, params)
        })
    })
Copy the code

Or create a server using http.createserver and do some pre-configuration work, such as multi-language configuration. In fact, a new Node Server is created inside Next. Js, and the Server class is used to complete most of the rendering work. Not only that, but this class also includes component rendering, route matching, error processing, cache processing and other links. Of course, to understand the source code rendering mechanism, Node knowledge is essential, so I won’t go into depth here.

How do you implement a server rendering

Here is the warehouse address: the simplest server render project

React server render

React: Client/server isomorphism

1. Build the compile and run environment

Install babel-node: NPM install bable-cli -g; Install the compiled React components:

npm install babel-preset-react -S
npm install babel-preset-env -S
npm install babel-plugin-transform-decorators-legacy -S
Copy the code

In package.json setup command launch command:

corss-env NODE_ENV=test nodemon --exec babel-node src/server.js
Copy the code

Cross-env has the courage to set environment variables; Nodemon monitors the file changes and reruns the command. Configure Babel(basic Usage and format) in. Babelrc, so you can do the following:

{
    "presets": [
        "env"."react"]."plugins": [
        "transform-decorators-legacy"]}Copy the code
2. Write service server.js

Create a new server.js and complete the first experiment:

import express from 'express'
var app = express()
app.get('/', (req, res) => {
    res.send('<h1>hello express</h1>')
})
app.listen(3000.function() {
    console.log('server started ! ')})Copy the code

Start the command to access localhost:3000

npm run server
Copy the code

Here is the warehouse address: the simplest server render project

3. How does the React component render

There are two ways to start

  1. RenderToString: Convert the React Component to an HTML string, and the generated DOM will have additional properties: each DOM will have onedata-react-idProperty, the first DOM will havedata-checksumProperties.
  2. RenderToStatucMarkup: Converts the React Component to an HTML string, but without additional attributes.

For example, if you want to render React, you need to convert the component to HTML using renderToString:

server.js:

import App from './components/App'
import React from 'react'
import {renderToString} from 'react-dom/server'

var app = express();

app.get("/", (req, res) => {
  const list = [1.2.3.4.5]
  const html = renderToString(<App list={list} />)
  res.send(html)
})
app.listen(3000, function () {
  console.log('server start !')
})

Copy the code

App.js:

import React from 'react'

export default class App extends React.Component {
  render() {
    return(
      <div>
        <ul>
          {
            this.props.list.map(item => {
              return <li>{item}</li>
            })
          }
        </ul>
      </div>
    )
  }
}
Copy the code

Access localhost:3000 to get the following result:

React server render

React isomorphic rendering

React rendering can only be done on the server side. Client rendering is not implemented yet. What isomorphism means is that the client and the server use the same components, the server is responsible for the first rendering, and the behavior and interaction is done by the client.

Next we render with React isomorphism:

  1. usecreate-ract-appScaffolding creates react project
  2. Combine express and create-React-app configuration files
  3. Create-react-app public express:app.use('/', express.static("build"))

import express from "express"
import App from './App'
import React from 'react'
import {renderToString} from 'react-dom/server'
import fs from 'fs'

var app = express();

app.get("/", (req, res) => {
  const html = fs.readFileSync('./build/index.html')
  const content = renderToString(<App />)
  res.send(html.toString().replace('<div id="root"></div>', `<div id="root">${content}</div>`))
})

app.use('/', express.static('build'))

app.listen(3000, function () {
  console.log('server start !')
})

Copy the code

The procedure described above is to create a build file, and then the server replaces the generated build file with the existing HTML and sends it to the client so that the client and server content will be consistent.

How to get the result: first run NPM run build to generate build file, then run NPM run server to access localhost:3000

React: Client/server isomorphism

Four, the last

Next. Js has a number of advantages; we no longer have to implement a server-side rendering ourselves. Now learn it and use it.