Why use next.js

React /vue/ Angular: It is a single page application, but the first screen load is too slow, which is not good for SEO. Next. Js is a lightweight React server rendering application framework.

Next. The advantages of js

  • Set up easily
  • Built-in DATA synchronization SSR
  • There are rich plugins that form their own ecology
  • Flexible configuration

Next. Js simple project construction

$NPX create-next-app next-demo //next-demo is the project name Enter http://localhost:3000/ in the browser to check whether the project is successfully generatedCopy the code

Introduction to the project structure of next.js

Every page is a React component.

  • Components folder: Used to store common or specialized components.
  • Node_modules: This is where all the dependencies for the Next project are, so you don’t normally have to modify or edit the content.
  • Pages folder: this is where pages are placed. The content of the side here will automatically generate routes and be rendered on the server side. After rendering, data will be synchronized.
  • Static folder: This is a static folder, such as the project needs images, ICONS, CSS files and other static resources can be placed here.

An introduction to routing for next.js

{/* link can only have a root element, cannot have parallel sibling elements, so can use a tag to wrap */} import link from {/* link can only have a root element, cannot have parallel sibling elements, so can use a tag to wrap */'next/link';
  <Link href="/jspangA"><a> a page </a></Link> // ② Programmatic jump coupling is low'next/router'; 
   function testRouterDemo(){
    Router.push({
      pathname: '/test'})} 2. Route parameter transmission // Can only use query? Id = 1 Does not support path:id. <Link href="/test? name=one"</a></Link> <Link href={{pathname:'/test', query: {name: 'test'}}><a> tag </ A ></Link> ②function gotoBlue(){
    Router.push({
      pathname: '/test',
      query: {name: 'one'} {withRouter} import {withRouter} from {withRouter} import {withRouter} from} import {withRouter} from'next/router'// Import Link from to accept arguments'next/link'Const GetParamCom = ({router})=>{// If withRouter is not introduced, there are no arguments in this functionreturn</div> <Link href= <div>{router.query.name}"/"</a></Link> </>)}exportDefault withRouter(GetParamCom) // withRouter is equipped with routing skillsCopy the code
Hook event for the route // routeChangeStart ==> Before the route changes // routeChangeComplete ==> When the end change occurs // beforeHistoryChange ==> browserhistoryRouteChangeError ==> When a route redirect error occurs //hashChangeStart ==> convert tohashRouting mode starts //hashChangeComplete === "transforms intohashThe routing mode is completeCopy the code

An introduction to the static method of getInitialProps for next.js

When the page is initially loaded, getInitialProps is only loaded on the server. The client only executes getInitialProps when a route jump (Link component jump or API method jump) occurs. GetInitialProps is an extension of the React lifecycle. It is a great invention of Next. Js, which is an important way to implement server rendering. Then use the obtained data as props to start the React component’s original lifecycle. We don’t care when getInitialProps is called, we can just hand that over to next.js.

The getInitialProps static method is used to get data from the remote end, which is the convention of the framework, so we want to follow the convention of the framework and not try to get data from the remote end during the lifecycle. Note: getInitialProps will not be used in child components. It can only be used in pages pages.

Example: const Test = ({list}) => {// Because the key of the remote data requested by getInitialProps is list, it can be used directly in this componentreturn(<> <div>{list}</div> </>)} test.getInitialprops = async() => {// Async () const Promise = new Promise((resolve) => { axios('Interface request address').then(
      (res) => {
        console.log('result:', res); resolve(res.data.data); })})return await promise;
}

export default Test; 
Copy the code

A brief introduction to the input object for getInitialProps

  • Pathname – The path part of the URL
  • Query-the Query part of the URL, which is parsed into objects
  • AsPath – The actual path (including the query part) displayed in the browser is of type String
  • Req-http request object (server-side only)
  • Res-http return object (server side only)
  • JsonPageRes – Get the data response object (only available on the client)
  • Err – Any errors in the rendering process
eg.
 Test.getInitialProps = async( { pathname } ) => { 
  const promise = new Promise((resolve) => {
    axios('Interface request address').then((res) => {console.log(pathname) // Can help get the path part of the URL})})return await promise;
}
 

Copy the code

Use Style JSX to write CSS styles

When you add the Style JSX code, Next. Js automatically adds a random class name, which prevents global CSS contamination

// next is an unsupported CSS file import React, {useState} from'react';
function Style(){
  const [color, setColor] = useState('blue');
  const changeColor = () => {
    setColor(color === 'blue' ? 'red ' : 'blue');
  }

  return (
    <>
      <span className="test"<style JSX </span> <div><button onClick={changeColor}> </ style JSX > {' div{color: red;${color}} .test{color: red; } `} </style> </> ) }export default Style;
Copy the code

Lazy loading of modules

  • React lazily loads modules.
  • Lazy loading is a common scenario: lazy loading is not the main business logic, so there is no need to load these external libraries in a timely manner
We use the external moment library as a template to test import React, {useState} from'react';

function Time(){
  const [time, SetTime] = useState(Date.now());
  const formatTime = async() => {
    const moment = await import('moment'); SetTime(moment.default(date.now ()).format())} SetTime(moment.default(date.now ()).format())}return<> <div> <button onClick={formatTime}> </button>export default Time;

Copy the code
  • Lazy loading of custom components
import React, {useState}  from 'react';
import dynamic from 'next/dynamic'; Const CustomCom = dynamic(import('.. /components/customCom')); // only when CustomCom is rendered will it be loaded, as the console can seefunction CustomComponent() {return (
    <>
     <CustomCom></CustomCom>
    </>
  )
}

export default CustomComponent;

Copy the code

How to use the Ant-Design UI framework in next.js

The first problem is solving the problem of Next-js support for CSS:

1. NPM install -- save@zeit /next-css // Const withCss = require()'@zeit/next-css')
    if(typeof require ! = ='undefined'){
        require.extensions['.css']=file=>{} } module.exports = withCss({}) 3. Wouldn't it be nice to restart the service and write CSS files in NextCopy the code

Load Ant’s modules as needed

1. npm install --save babel-plugin-import 2. After the installation is complete, create the. Babelrc file in the project root directory and write the following configuration file. {"presets": ["next/babel"], // next.js's total configuration file inherits all of its own configuration"plugins"[// add a new plugin that allows ANTD to be introduced on demand, including CSS ["import",
            {
                "libraryName":"antd"."style":"css"}}]]Copy the code

conclusion

Hope this simple introduction can bring a little help to the small partners in need of ha ~😊