国产探花免费观看_亚洲丰满少妇自慰呻吟_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>    );  }}            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 商丘市| 女性| 剑川县| 河津市| 印江| 遂川县| 察隅县| 张掖市| 临沧市| 陆川县| 赣榆县| 安康市| 湖南省| 兴业县| 嵩明县| 兴和县| 怀远县| 永平县| 峨眉山市| 军事| 兰州市| 大悟县| 揭东县| 黄山市| 米脂县| 余干县| 镇康县| 莎车县| 巨野县| 彭州市| 房山区| 广昌县| 洞口县| 老河口市| 庆云县| 宝山区| 惠水县| 天台县| 剑河县| 台北市| 绵阳市|