首页 > 语言 > JavaScript > 正文

Next.js实现react服务器端渲染的方法示例

2024-05-06 15:43:33
字体:
来源:转载
供稿:网友

说明

实现 路由跳转、redux

文件版本

“next”: “^4.2.3”, “react”: “^16.2.0”, “react-dom”: “^16.2.0”

Next.js GitHub 文档

项目源码

使用

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 覆盖历史跳转 */}      <Link href={href} replace>      <a>click to home index page</a>      </Link>    </div>    );  }}            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选