說明
實現 路由跳轉、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) - 跳轉頁面 */
更好的方式使用路由 主站蜘蛛池模板: 大姚县| 清镇市| 黑水县| 桐城市| 徐州市| 淅川县| 额济纳旗| 桐乡市| 永州市| 桃源县| 龙山县| 玉门市| 台中市| 阳朔县| 乐都县| 宜章县| 荥经县| 宁安市| 宝山区| 将乐县| 西城区| 新乡县| 西安市| 洪泽县| 清涧县| 清河县| 昌乐县| 蒙阴县| 成武县| 唐河县| 江阴市| 肥东县| 新乐市| 保定市| 北碚区| 古交市| 常德市| 砚山县| 福海县| 海原县| 常德市|