国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > 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>    );  }}            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 桑植县| 商都县| 会昌县| 瑞金市| 那坡县| 上饶市| 平远县| 涞水县| 大英县| 资中县| 靖西县| 伊宁市| 沙坪坝区| 利津县| 平阴县| 兴安盟| 青海省| 赫章县| 吴桥县| 镇远县| 昌吉市| 莒南县| 景泰县| 通许县| 综艺| 晋江市| 冷水江市| 尖扎县| 遵义县| 江口县| 上蔡县| 三明市| 疏勒县| 鲁山县| 楚雄市| 肃南| 大丰市| 株洲县| 文登市| 台州市| 伊春市|