說明
實現 路由跳轉、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> ); }}
新聞熱點
疑難解答
圖片精選