說明
實現 路由跳轉、redux
文件版本
使用
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> ); }}7. 使用內置 router 方法,手動觸發路由跳轉
next/router 提供一套方法和屬性,幫助確認當前頁面路由參數,和手動觸發路由跳轉
import router from 'next/router'; /* router.pathname ==> /home router.query ==> {} router.route - 當前路由 asPath - 顯示在瀏覽器地址欄的實際的路由 push(url, as=url) - 跳轉頁面的方法 replace(url, as=url) - 跳轉頁面 */更好的方式使用路由 主站蜘蛛池模板: 石屏县| 四川省| 达尔| 彰化市| 正镶白旗| 鸡泽县| 班戈县| 安福县| 齐齐哈尔市| 呼伦贝尔市| 沁源县| 北海市| 嘉黎县| 武川县| 武邑县| 辛集市| 新和县| 乳源| 高陵县| 开阳县| 兰溪市| 乌兰察布市| 昔阳县| 贵港市| 乌什县| 阿尔山市| 获嘉县| 改则县| 高平市| 香港| 英吉沙县| 万宁市| 保山市| 和政县| 浙江省| 大丰市| 洛南县| 哈尔滨市| 日土县| 隆化县| 信阳市|