- website
- React Server rendering framework Next-js
- Next. Js app’s official website
- Next. Js app’s official website 2
Next, a brief introduction of js
- Next. Js is a lightweight React server rendering application framework
- The React project architecture is easy to build. For example: Webpack configuration, server startup, routing configuration, caching capabilities, these have been perfected in its interior for us to build complete.
- The built-in data synchronization strategy solves the biggest difficulty in server rendering. Reusing server rendered data on the client side is very complicated and difficult without a framework. With Next. Js, it gives us a great solution that makes it easy to implement these steps.
- Flexible configuration makes development easier. It provides many flexible configuration items, which can be quickly and flexibly configured according to different project requirements.
- Next. Js is currently the best solution for React server rendering, so if you want to use React to develop SEO applications, you should basically use next.js.
advantages
- With Next. Js we can easily implement React server rendering to speed up the first screen opening and SEO (search engine optimization).
- When there is no Next. Js, React development requires a lot of complicated parameters, such as Webpack configuration, Router configuration and server configuration…. .
- If you need to do SEO, there are more things to consider. How to keep the server-side rendering consistent with the client-side rendering can be a very troublesome matter, requiring the introduction of many third-party libraries.
- But with next.js, these problems are solved, allowing developers to focus on business logic
Create the Next. Js project
Manually create
NPM install --save react react-dom next // install react-dom next { "test": "echo \"Error: no test specified\" && exit 1", "dev" : "next" , "build" : " next build", "start" : "Next start"} // configure package.json, add shortcut command 4. When you create the Pages folder (the name of which is specified by next), next.js automatically creates the route, 5. NPM run dev // Run Run the NPM run dev command and open http://localhost:3000. If you want to use another port, run NPM run dev -- -p < set port number >. 'NPM run dev -- -p 3080' : ready-started server on http://localhost:3080Copy the code
NPM run dev -- -p 3080 > [email protected] dev /Users/mavis/gitHub/2020_react/next. Js-demo > next ready-started server on http://localhost:3080 (node:43465) ExperimentalWarning: The fs.promises API is experimental event - compiled successfullyCopy the code
Create-next-app (scaffolding) to create
NPX is the built-in NPM module of Node, so you can use the NPX command directly whenever you install Node.
NPM install -g NPX // install global next.js 2. NPX create-next-app next-create // create project 3Copy the code
Project Structure Introduction
- Components places common components (not including pages)
- Node_modules depend on the package
- Pages is where static files are placed. Some pages, the content here will automatically generate routes and render in the server. After rendering, data will be synchronized
- Static folder, place some pictures and static resources
- .gitignore Ignores submitting Git upload files
- Json file configuration information (name, version, license) is primarily used by NPM install to download dependencies
Routing – Basic and basic jumps
1. The Link and the Router
import React from 'react' import Link from 'next/link' import Router from 'next/router' const Home = () => { function gotoA() { Router.push({ pathname: '/IndexB', query: { name: <div><Link href="/indexA? <button onClick={gotoA}> </button></div> </div>) export default HomeCopy the code
2. Send values and receive parameters
Receiving passed arguments in next.js can only be done through query (? Id =1) instead of (path:id)
Import Link from 'next/ Link 'import {withRouter} from 'next/router' Const IndexA = ({router})=>(<div> <div>Index -a page. Name :{router.query.name}</div> <Link Export default withRouter(IndexA) href="/"><a>Copy the code
3. Route six hook events
Router.events.on() is used to listen for events when a route changes
import Router from 'next/router' import { withRouter} from 'next/router' const routerChange = ({ router }) => { Router.events.on('routeChangeStart', (... Args) => {console.log('1. RouteChangeStart -> Route starts to change, parameter :',... args) }) Router.events.on('routeChangeComplete', (... Args) => {console.log('2.routeChangeComplete-> Route end change, parameter :',... args) }) Router.events.on('beforeHistoryChange', (... Args) => {console.log('3.beforeHistoryChange-> Triggered before changing browser history with :',... args) }) Router.events.on('routeChangeError', (... Args) => {console.log('4. RouteChangeError -> jump error, parameter :',... args) }) Router.events.on('hashChangeStart', (... Args) => {console.log('5. HashChangeStart -> Hash jump starts when executed with :',... args) }) Router.events.on('hashChangeComplete', (... Args) => {console.log('6. HashChangeComplete -> Hash jump is complete, parameter is :',... Args)}) return (<div> routerChange page <br /> <Link href="/"><a> </a></Link><br /> <div> <Link href="#hash"><a>hash</a></Link> </div> <div> <Link href="/indexA? name=ldd"><a>indexA</a></Link> </div> </div> ) } export default routerChangeCopy the code
Get the data using Axios in getInitialProps
Next.js provides static methods for getInitialProps to get data. Instead of getting data in componentDidMount, getInitialProps is the greatest invention of next.js. It defines a specification for next.js. GetInitialProps is an async function, so you can use the await keyword in the getInitialProps function to program asynchronous logic synchronously
routerChange.getInitialProps = async () => { const promise = new Promise((resolve) => { Axios (' https://www.easy-mock.com/mock/5dc0d5b143ff8e61fd932abe/example/query '). Then ((res) = > {the console. The log (' remote data results: ', res) resolve(res.data.data) } ) }) return await promise }Copy the code
Write the syntax using Style JSX syntax and Antd
1. style
Next. Js does not support CSS, so it cannot be imported with import. If it is used, it needs to be configured separately (b. It explains how to configure it.)
import Link from 'next/link' import { withRouter } from 'next/router' const IndexA = ({ router }) => ( <div> <div ClassName ="name">Index-A page. name:{router.query.name}</div> <p> < / p > < Link href = "/" > < a > to return to the home page < / a > < / Link > < style JSX > {`. Name {color: red; } p { background: pink; } ` } </style> </div> ) export default withRouter(IndexA)Copy the code
Using Style JSX will automatically add a random class name to next.js
2. The configuration of CSS
Yarn add@zeit /next-css 2. Create a next. Config. js file in the root directory. Restart the code to runCopy the code
When we package Ant Design, we pack all of the Ant Design packages, which can cause performance problems and make the project load very slow. This is definitely not going to work. The goal is to load only the modules used in the project, which requires a babel-plugin-import file. After the installation is complete, create the. Babelrc file in the project root directory
1. yarn add antd 2. yarn add babel-plugin-import 3. Babelrc file {"presets":["next/ Babel "], // next.js general configuration file, which is equivalent to inherits all of its own configuration "plugins":[// add a new plugin, which allows antD to import on demand, Including CSS [" import ", {" libraryName ":" antd ", "style" : "CSS"}]]}Copy the code
Once configured, WebPack does not pack the entire Ant Design package into production by default. Instead, we pack the component as we use it, and CSS is packaged on demand.
With the above configuration, you can happily use Ant Desgin in next.js to make your pages look better.
The custom<Head>
More friendly SEO operations
1. Method 1: Add to each page<Head>
Create header.js in the pages file
import React from 'react'; import Head from 'next/head'; Const Header = ()=>(<div> <Head> <title> Learn next.js </title> <meta charSet=' utF-8 '/> </Head> <div> next.js is a lightweight React The server renders the application framework. </div> </div> ) export default HeaderCopy the code