Next.js实现react服务器端渲染的方法示例
网络编程 2021-07-04 15:49www.168986.cn编程入门
这篇文章主要介绍了Next.js实现react服务器端渲染的方法示例,长沙网络推广觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随长沙网络推广过来看看吧
说明
实现 路由跳转、redux
文件版本
- “next”: “^4.2.3”,
- “react”: “^16.2.0”,
- “react-dom”: “^16.2.0”
使用
Next.js 使用文件体统作为API,可以自动进行服务器端渲染和代码分割
1. 安装
yarn add next react react-dom
2. package.json 中添加 npm script
"scripts": { "dev": "next", "build": "next build", "start": "next start" },
3. 创建 /pages 文件夹,其中文件会映射为路由
/pages 文件夹是顶级组件文件夹 其中 /pages/index.js 文件会映射文 / 路由,其他文件根据文件名映射
目录结构 | 映射路由 |
---|---|
/pages/index.js | / |
/pages/about.js | /about |
/pages/home/index.js | /home |
/pages/home/about.js | /home/about |
每一个路由js文件都会 export 一个 React 组件,这个组件可以是函数式的也可以是通过集成 React.Component 得到的类
export default () => <div>this is index page </div>;
4. 创建 /static 文件夹,存放静态资源
静态资源文件夹文件会映射到 /static/ 路由下,直接通过 http://localhost:3000/static/test.png 访问
5. 使用内置组件 <head> 定制每个页面的 head 部分
import Head from 'next/head'; // 引入内置组件 export default () => ( <div> <Head> <title>index page</title> <meta name="viewport" content="initial-scale=1.0, width=device-width"/> </Head> <div>this is index page</div> </div> );
6. 使用内置组件 <Link> 进行路由跳转
import Link from 'next/link'; export default () => ( <div> <p>this is home index page</p> <Link href="/about" rel="external nofollow" rel="external nofollow" > <a> to about page</a> </Link> </div> );
更多 Link 使用方式
import React, {Component} from 'react'; import Link from 'next/link'; export default class About extends Component { constructor(props) { super(props); } render() { // href 值可以是一个对象 const href = { pathname: '/home', query: {name: 'test'} }; return ( <div> <p>this is about page </p> <img src="/static/test.png" alt="test"/> {/* replace 覆盖历史跳转 *
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程