导航菜单

  • 0.api
  • 0.Async
  • 0.module
  • 1.ES2015
  • 2.Promise
  • 3.Node
  • 4.NodeInstall
  • 5.REPL
  • 6.NodeCore
  • 7.module&NPM
  • 8.Encoding
  • 9.Buffer
  • 10.fs
  • 11.Stream-1
  • 11.Stream-2
  • 11.Stream-3
  • 11.Stream-4
  • 12-Network-2
  • 12.NetWork-3
  • 12.Network-1
  • 13.tcp
  • 14.http-1
  • 14.http-2
  • 15.compress
  • 16.crypto
  • 17.process
  • 18.yargs
  • 19.cache
  • 20.action
  • 21.https
  • 22.cookie
  • 23.session
  • 24.express-1
  • 24.express-2
  • 24.express-3
  • 24.express-4
  • 25.koa-1
  • 26.webpack-1-basic
  • 26.webpack-2-optimize
  • 26.webpack-3-file
  • 26.webpack-4.tapable
  • 26.webpack-5-AST
  • 26.webpack-6-sources
  • 26.webpack-7-loader
  • 26.webpack-8-plugin
  • 26.webpack-9-hand
  • 26.webpack-10-prepare
  • 28.redux
  • 28.redux-jwt-back
  • 28.redux-jwt-front
  • 29.mongodb-1
  • 29.mongodb-2
  • 29.mongodb-3
  • 29.mongodb-4
  • 29.mongodb-5
  • 29.mongodb-6
  • 30.cms-1-mysql
  • 30.cms-2-mysql
  • 30.cms-3-mysql
  • 30.cms-4-nunjucks
  • 30.cms-5-mock
  • 30.cms-6-egg
  • 30.cms-7-api
  • 30.cms-8-roadhog
  • 30.cms-9-yaml
  • 30.cms-10-umi
  • 30.cms-12-dva
  • 30.cms-13-dva-ant
  • 30.cms-14-front
  • 30.cms-15-deploy
  • 31.dva
  • 31.cms-13-dva-antdesign
  • 33.redis
  • 34.unittest
  • 35.jwt
  • 36.websocket-1
  • 36.websocket-2
  • 38.chat-api-1
  • 38.chat-api-2
  • 38.chat-3
  • 38.chat-api-3
  • 38.chat
  • 38.chat2
  • 38.chat2
  • 39.crawl-0
  • 39.crawl-1
  • 39.crawl-2
  • 40.deploy
  • 41.safe
  • 42.test
  • 43.nginx
  • 44.enzyme
  • 45.docker
  • 46.elastic
  • 47.oauth
  • 48.wxpay
  • index
  • 52.UML
  • 53.design
  • index
  • 54.linux
  • 57.ts
  • 56.react-ssr
  • 58.ts_react
  • 59.ketang
  • 59.ketang2
  • 61.1.devops-linux
  • 61.2.devops-vi
  • 61.3.devops-user
  • 61.4.devops-auth
  • 61.5.devops-shell
  • 61.6.devops-install
  • 61.7.devops-system
  • 61.8.devops-service
  • 61.9.devops-network
  • 61.10.devops-nginx
  • 61.11.devops-docker
  • 61.12.devops-jekins
  • 61.13.devops-groovy
  • 61.14.devops-php
  • 61.15.devops-java
  • 61.16.devops-node
  • 61.17.devops-k8s
  • 62.1.react-basic
  • 62.2.react-state
  • 62.3.react-high
  • 62.4.react-optimize
  • 62.5.react-hooks
  • 62.6.react-immutable
  • 62.7.react-mobx
  • 62.8.react-source
  • 63.1.redux
  • 63.2.redux-middleware
  • 63.3.redux-hooks
  • 63.4.redux-saga
  • 63.5.redux-saga-hand
  • 64.1.router
  • 64.2.router-connected
  • 65.1.typescript
  • 65.2.typescript
  • 65.3.typescript
  • 65.4.antd
  • 65.4.definition
  • 66-1.vue-base
  • 66-2.vue-component
  • 66-3.vue-cli3.0
  • 66-4.$message组件
  • 66-5.Form组件
  • 66-6.tree
  • 66-7.vue-router-apply
  • 66-8.axios-apply
  • 66-9.vuex-apply
  • 66-10.jwt-vue
  • 66-11.vue-ssr
  • 66-12.nuxt-apply
  • 66-13.pwa
  • 66-14.vue单元测试
  • 66-15.权限校验
  • 67-1-network
  • 68-2-wireshark
  • 7.npm2
  • 69-hooks
  • 70-deploy
  • 71-hmr
  • 72.deploy
  • 73.import
  • 74.mobile
  • 75.webpack-1.文件分析
  • 75.webpack-2.loader
  • 75.webpack-3.源码流程
  • 75.webpack-4.tapable
  • 75.webpack-5.prepare
  • 75.webpack-6.resolve
  • 75.webpack-7.loader
  • 75.webpack-8.module
  • 75.webpack-9.chunk
  • 75.webpack-10.asset
  • 75.webpack-11.实现
  • 76.react_optimize
  • 77.ts_ketang_back
  • 77.ts_ketang_front
  • 78.vue-domdiff
  • 79.grammar
  • 80.tree
  • 81.axios
  • 82.1.react
  • 82.2.react-high
  • 82.3.react-router
  • 82.4.redux
  • 82.5.redux_middleware
  • 82.6.connected
  • 82.7.saga
  • 82.8.dva
  • 82.8.dva-source
  • 82.9.roadhog
  • 82.10.umi
  • 82.11.antdesign
  • 82.12.ketang-front
  • 82.12.ketang-back
  • 83.upload
  • 84.graphql
  • 85.antpro
  • 86.1.uml
  • 86.2.design
  • 87.postcss
  • 88.react16-1
  • 89.nextjs
  • 90.react-test
  • 91.react-ts
  • 92.rbac
  • 93.tsnode
  • 94.1.JavaScript
  • 94.2.JavaScript
  • 94.3.MODULE
  • 94.4.EventLoop
  • 94.5.文件上传
  • 94.6.https
  • 94.7. nginx
  • 95.1. react
  • 95.2.react
  • 96.1.react16
  • 96.2.fiber
  • 96.3.fiber
  • 97.serverless
  • 98.websocket
  • 100.1.react-basic
  • 101.1.monitor
  • 101.2.monitor
  • 102.java
  • 103.1.webpack-usage
  • 103.2.webpack-bundle
  • 103.3.webpack-ast
  • 103.4.webpack-flow
  • 103.5.webpack-loader
  • 103.6.webpack-tapable
  • 103.7.webpack-plugin
  • 103.8.webpack-optimize1
  • 103.9.webpack-optimize2
  • 103.10.webpack-hand
  • 103.11.webpack-hmr
  • 103.11.webpack5
  • 103.13.splitChunks
  • 103.14.webpack-sourcemap
  • 103.15.webpack-compiler1
  • 103.15.webpack-compiler2
  • 103.16.rollup.1
  • 103.16.rollup.2
  • 103.16.rollup.3
  • 103.16.vite.basic
  • 103.16.vite.source
  • 103.16.vite.plugin
  • 103.16.vite.1
  • 103.16.vite.2
  • 103.17.polyfill
  • 104.1.binary
  • 104.2.binary
  • 105.skeleton
  • 106.1.react
  • 106.2.react_hooks
  • 106.3.react_router
  • 106.4.redux
  • 106.5.redux_middleware
  • 106.6.connected-react-router
  • 106.6.redux-first-history
  • 106.7.redux-saga
  • 106.8.dva
  • 106.9.umi
  • 106.10.ketang
  • 106.11.antdesign
  • 106.12.antpro
  • 106.13.router-6
  • 106.14.ssr
  • 106.15.nextjs
  • 106.16.1.cms
  • 106.16.2.cms
  • 106.16.3.cms
  • 106.16.4.cms
  • 106.16.mobx
  • 106.17.fomily
  • 107.fiber
  • 108.http
  • 109.1.webpack_usage
  • 109.2.webpack_source
  • 109.3.dll
  • 110.nest.js
  • 111.xstate
  • 112.Form
  • 113.redux-saga
  • 114.react+typescript
  • 115.immer
  • 116.pro5
  • 117.css-loader
  • 118.1.umi-core
  • 119.2.module-federation
  • 119.1.module-federation
  • 120.create-react-app
  • 121.react-scripts
  • 122.react-optimize
  • 123.jsx-runtime
  • 124.next.js
  • 125.1.linux
  • 125.2.linux-vi
  • 125.3.linux-user
  • 125.4.linux-auth
  • 125.5.linux-shell
  • 125.6.linux-install
  • 125.7.linux-system
  • 125.8.linux-service
  • 125.9.linux-network
  • 125.10.nginx
  • 125.11.docker
  • 125.12.ci
  • 125.13.k8s
  • 125.14.k8s
  • 125.15.k8s
  • 125.16.k8s
  • 126.11.react-1
  • 126.12.react-2
  • 126.12.react-3
  • 126.12.react-4
  • 126.12.react-5
  • 126.12.react-6
  • 126.12.react-7
  • 126.12.react-8
  • 127.frontend
  • 128.rollup
  • 129.px2rem-loader
  • 130.health
  • 131.hooks
  • 132.keepalive
  • 133.vue-cli
  • 134.react18
  • 134.2.react18
  • 134.3.react18
  • 135.function
  • 136.toolkit
  • 137.lerna
  • 138.create-vite
  • 139.cli
  • 140.antd
  • 141.react-dnd
  • 142.1.link
  • 143.1.gulp
  • 143.2.stream
  • 143.3.gulp
  • 144.1.closure
  • 144.2.v8
  • 144.3.gc
  • 145.react-router-v6
  • 146.browser
  • 147.lighthouse
  • 148.1.basic
  • 148.2.basic
  • 148.3.basic
  • 148.4.basic
  • 148.5.basic
  • 149.1.vite
  • 149.2.vite
  • 149.3.vite
  • 149.4.vite
  • 150.react-window
  • 151.react-query
  • 152.useRequest
  • 153.transition
  • 154.emotion
  • 155.1.formily
  • 155.2.formily
  • 155.3.formily
  • 155.3.1.mobx.usage
  • 155.3.2.mobx.source
  • 156.vue-loader
  • 103.11.mf
  • 157.1.react18
  • 158.umi4
  • 159.rxjs
  • 159.rxjs2
  • 160.bff
  • 161.zustand
  • 162.vscode
  • 163.emp
  • 164.cors
  • 1. 同构
  • 2.Next.js
  • 3.初始化
    • 3.1 创建项目
    • 3.2 创建脚本
    • 3.3 访问
  • 4.跑通路由
    • 4.1 知识点
    • 4.2 安装依赖包
    • 4.3 .babelrc
    • 4.4 next.config.js
    • 4.5 pages_app.tsx
    • 4.6 pages\index.tsx
    • 4.7 pages\user.tsx
    • 4.8 pages\profile.tsx
  • 5.二级路由
    • 5.1 知识点
    • 5.2 执行顺序
      • 5.2.1 后台顺序
      • 5.2.2 前台顺序
    • 5.3 pages_app.tsx
    • 5.4 user\index.tsx
    • 5.5 user\list.tsx
    • 5.6 user\add.tsx
  • 6.集成koa
    • 6.1 知识点
    • 6.2 安装依赖
    • 6.3 client\index.js
    • 6.4 package.json
  • 7.调用接口
    • 7.1 utils\axios.tsx
    • 7.2 pages\user\add.tsx
    • 7.3 user\list.tsx
  • 8.用户详情
    • 8.1 知识点
    • 8.2 user\detail.tsx
    • 8.2 components\UserInfo.tsx
    • 8.3 client\index.js
  • 9.登录
    • 9.1 pages\login.tsx
  • 10.集成redux
    • 10.1 安装依赖
    • 10.2 pages_app.tsx
    • 10.3 user\add.tsx
    • 10.4 action-types.tsx
    • 10.5 store\index.tsx
  • 11.loading效果
    • 11.1 pages_app.tsx
  • 12.受保护路由
    • 12.1 pages\profile.tsx
  • 13.自定义Document
    • 13.1 pages_document.js
    • 13.2 pages\index.tsx
  • 14.服务端
    • 14.1 api\index.js
    • 14.2 api\config.js
    • 14.3 api\db.js

1. 同构 #

  • 同构的项目支持客户端渲染和服务器端渲染
  • 客户端渲染缺点
    • 首屏速度加载慢
    • 不支持SEO和搜索引擎优化
    • 首页需要通过请求初始化数据

renderflow

2.Next.js #

  • Next.js英文文档 Next.js中文文档 是一个轻量级的 React 服务端渲染应用框架
  • 默认支持服务端渲染
  • 自动根据页面进行代码分割
  • 基于页面的客户端路由方案
  • 基于 Webpack 的开发环境,支持热模块替换
  • 可以跟Koa或者其它Node.js服务器进行集成
  • 支持 Babel 和 Webpack 的配置项定制
  • 静态文件服务 public

3.初始化 #

3.1 创建项目 #

mkdir zhufengnextjs
cd zhufengnextjs
npm init -y
yarn add --dev typescript react @types/react react-dom @types/node next axios
mkdir pages

3.2 创建脚本 #

package.json

{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  }
}

https://github.com/zeit/next.js/blob/canary/.gitignore

3.3 访问 #

  • 以 ./pages作为服务端的渲染和索引的根目录
  • public静态文件服务映射
  • pages组件代码自动分割

index.tsx

export default function () {
    return (
        <div>Home</div>
    )
}
curl http://localhost:3000/

4.跑通路由 #

4.1 知识点 #

  • 绑定 styled-jsx 来生成独立作用域的 CSS
  • 如何支持css
  • 如何支持antd并实现按需加载
  • 路由的使用和两种跳转路径的方法

4.2 安装依赖包 #

yarn add @zeit/next-css antd babel-plugin-import

4.3 .babelrc #

.babelrc

{
    "presets": [
        "next/babel"
    ],
    "plugins": [
        [
            "import",
            {
                "libraryName": "antd"
            }
        ]
    ]
}

4.4 next.config.js #

  • next-css可以让你在项目中引用CSS

next.config.js

const withCSS = require('@zeit/next-css');

if (typeof require !== 'undefined') {
    require.extensions['.css'] = file => { }
}

module.exports = withCSS({})

4.5 pages_app.tsx #

  • App组件来初始化页面,你可以重写它来控制页面初始化
    • 当页面变化时保持页面布局
    • 当路由变化时保持页面状态
    • 注入额外数据到页面里

pages_app.tsx

import App, { Container } from 'next/app';
import Link from 'next/link';
import { Layout, Menu, Icon } from 'antd';
import 'antd/dist/antd.css';
import { withRouter } from 'next/router';
const { Header, Footer } = Layout;
class LayoutApp extends App<any> {
    render() {
        let { Component } = this.props as any;
        let pathname = this.props.router.pathname;
        pathname = '/' + (pathname.split('/')[1]);
        return (
            <Container>
                <style jsx>
                     {`a{display:inline-block!important;}`}
                </style>
                <Layout>
                    <Header className="header">
                       <img src="/images/jglogo.png" style={{ width: 120, height: 31, margin: '16px 24px 16px 0px', float: 'left' }} />
                        <Menu theme="dark" mode="horizontal" style={{ lineHeight: '64px', display: 'inline-block' }}
                            selectedKeys={[pathname]} 
                            defaultSelectedKeys={[pathname]}>
                            <Menu.Item key="/">
                                <Icon type="home" /><Link href="/"><a>首页</a></Link>
                            </Menu.Item>
                            <Menu.Item key="/user">
                                <Icon type="/user" /> <Link href="/user" ><a>用户管理</a></Link>
                            </Menu.Item>
                            <Menu.Item key="/profile">
                                <Icon type="profile" /><Link href="/profile"><a>个人中心</a></Link>
                            </Menu.Item>
                            <Menu.Item key="/login">
                                <Icon type="login" /><Link href="/login"><a>登录</a></Link>
                            </Menu.Item>
                        </Menu>
                    </Header>
                    <Component />
                    <Footer style={{ textAlign: 'center' }} >@copyright 前端架构</Footer>
                </Layout>
            </Container>
        )
    }
}
export default withRouter(LayoutApp);

4.6 pages\index.tsx #

pages\index.tsx

import router from 'next/router'
import { Button, Layout } from 'antd';
const { Content } = Layout;
export default function () {
    return (
        <Content  style={{ margin: '20px auto' }}>
            <div>Home</div>
            <Button onClick={() => router.push('/user')}>/user</Button>
        </Content>

    )
}

4.7 pages\user.tsx #

pages\user.tsx

import router from 'next/router';
import { Button, Layout } from 'antd';
const { Content } = Layout;
export default function () {
    return (
        <Content  style={{ margin: '20px auto' }}>
            <div>User</div>
            <Button onClick={() => router.push('/profile')}>/profile</Button>
        </Content>
    )
}

4.8 pages\profile.tsx #

pages\profile.tsx

import router from 'next/router';
import { Button, Layout } from 'antd';
const { Content } = Layout;
export default function () {
    return (
        <Content  style={{ margin: '20px auto' }}>
            <div>Profile</div>
            <Button onClick={() => router.back()}>返回</Button>
        </Content>
    )
}

5.二级路由 #

5.1 知识点 #

  • 支持二级路由
  • 实现二级布局组件
  • 路由跳转传递参数
  • 页面组件通过getInitialProps获取数据

5.2 执行顺序 #

5.2.1 后台顺序 #

severflow.png

5.2.2 前台顺序 #

clientflow.png

5.3 pages_app.tsx #

pages_app.tsx

import App from 'next/app';
import Link from 'next/link';
import { Layout, Menu, Icon } from 'antd';
import 'antd/dist/antd.css';
import { withRouter } from 'next/router';
const { Header, Footer } = Layout;
class LayoutApp extends App<any> {
+    static async getInitialProps(params) {
+        if (params.ctx.req) params.ctx.req = 'req';
+        if (params.ctx.res) params.ctx.res = 'res';
+        console.log('1.LayoutApp.getInitialProps', params);
+        let { Component, ctx } = params;
+        let pageProps = {};
+        if (Component.getInitialProps)
+            pageProps = await Component.getInitialProps(ctx);
+        return { pageProps };
+    }
    render() {
+        console.log('3.LayoutApp.render', this.props);
        let { Component } = this.props as any;
        let pathname = this.props.router.pathname;
        pathname = '/' + (pathname.split('/')[1]);
        return (
            <>
                <style jsx>
+                    {`a{display:inline-block!important;}`}
                </style>
                <Layout>
                    <Header className="header">
+                        <img src="/images/jglogo.png" style={{ width: 120, height: 31, margin: '16px 24px 16px 0px', float: 'left' }} />
+                        <Menu theme="dark" mode="horizontal" style={{ lineHeight: '64px', display: 'inline-block' }}
                            selectedKeys={[pathname]}
                            defaultSelectedKeys={[pathname]}>
                            <Menu.Item key="/">
                                <Icon type="home" /><Link href="/"><a>首页</a></Link>
                            </Menu.Item>
                            <Menu.Item key="/user">
                                <Icon type="/user" /> <Link href="/user" ><a>用户管理</a></Link>
                            </Menu.Item>
                            <Menu.Item key="/profile">
                                <Icon type="profile" /><Link href="/profile"><a>个人中心</a></Link>
                            </Menu.Item>
                        </Menu>
                    </Header>
+                    <Component {...this.props.pageProps} />
                    <Footer style={{ textAlign: 'center' }} >@copyright 前端架构</Footer>
                </Layout>
            </>
        )
    }
}
export default withRouter(LayoutApp);

5.4 user\index.tsx #

pages\user\index.tsx

import { withRouter } from 'next/router';
import Link from 'next/link';
import { Layout, Menu, Icon } from 'antd';
const { Sider, Content } = Layout;
function UserLayout(props) {
    return (
        <>
            <style jsx>
                 {`a{display:inline-block!important;}`}
            </style>
            <Layout>
                <Sider>
                    <Menu
                        theme="dark"
                        mode="inline"
                        defaultSelectedKeys={[props.router.pathname]}
                    >
                        <Menu.Item key="/user/list">
                            <Icon type="user" /><Link href="/user/list"><a>用户列表</a></Link>
                        </Menu.Item>
                        <Menu.Item key="/user/add">
                            <Icon type="plus" /><Link href="/user/add"><a>添加用户</a></Link>
                        </Menu.Item>
                    </Menu>
                </Sider>
                <Content style={{ padding: 8 }}>
                    {props.children}
                </Content>
            </Layout>
        </>
    )
}
export default withRouter(UserLayout);

5.5 user\list.tsx #

pages\user\list.tsx

import UserLayout from './index';
import { List } from 'antd';
import Link from 'next/link';
function UseList(props) {
    console.log('4.UseList.render', props);
    return (
        <UserLayout>
            <List
                header={<div>用户列表</div>}
                footer={<div>共计多少{props.list.length}个用户</div>}
                bordered
                dataSource={props.list}
                renderItem={(item: any) => (
                    <List.Item key={item._id}>
                        <Link as={`/user/detail/${item._id}`} href={{ pathname: `/user/detail`, query: { id: item._id } }}><a>{item.username}</a></Link>
                    </List.Item>
                )}
            />
        </UserLayout>
    )
}

UseList.getInitialProps = async (ctx) => {
    if (ctx.req) { ctx.req = 'req'; }
    if (ctx.res) { ctx.res = 'res'; }
    console.log('2.UseList.getInitialProps ctx', ctx);
    let list = [{ _id: 1, username: 'zhangsan', password: '1' }, { _id: 2, username: 'lisi', password: '2' }];
    return { list };
}

export default UseList;

5.6 user\add.tsx #

pages\user\add.tsx

import UserLayout from './index';
import router from 'next/router';
import { Form, Input, Button, Icon } from 'antd';
function UserAdd(props) {
    const { getFieldDecorator } = props.form;
    return (
        <UserLayout>
            <Form className="login-form" style={{ maxWidth: '300px' }}>
                <Form.Item>
                    {getFieldDecorator('username', {
                        rules: [{ required: true, message: 'Please input your username!' }],
                    })(
                        <Input
                            prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
                            placeholder="Username"
                        />,
                    )}
                </Form.Item>
                <Form.Item>
                    {getFieldDecorator('password', {
                        rules: [{ required: true, message: 'Please input your Password!' }],
                    })(
                        <Input
                            prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                            type="password"
                            placeholder="Password"
                        />,
                    )}
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit" className="login-form-button">
                        添加用户
                </Button>
                </Form.Item>
            </Form>
        </UserLayout>
    )
}
export default Form.create({ name: 'UserAdd' })(UserAdd);

6.集成koa #

  • Next自身的服务器只能处理SSR请求
  • 无法处理API接口的请求

6.1 知识点 #

  • 如何集成koa
  • 在koa使用next作中间件

6.2 安装依赖 #

yarn add koa koa-router

6.3 client\index.js #

client\index.js

let Koa = require('koa');
let Router = require('koa-router');
const next = require('next');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev: true });
const handler = app.getRequestHandler();
app.prepare().then(() => {
    const server = new Koa();
    let router = new Router();
    server.use(router.routes());
    server.use(async (ctx, next) => {
        await handler(ctx.req, ctx.res);
        ctx.response = false;
    });
    server.listen(3000, () => console.log('server started at port 3000'));
});

6.4 package.json #

package.json

  "scripts": {
+   "client": "nodemon client",
    "build": "next build",
    "start": "next start"
  },

7.调用接口 #

  • 添加用户
  • 查看用户列表
  • 当服务渲染时,getInitialProps将会把数据序列化,就像JSON.stringify
  • 所以确保getInitialProps返回的是一个普通 JS 对象,而不是Date, Map 或 Set类型
  • 当页面初始化加载时,getInitialProps只会加载在服务端。只有当路由跳转(Link组件跳转或 API 方法跳转)时,客户端才会执行getInitialProps
  • getInitialProps将不能使用在子组件中。只能使用在pages页面中
  • getInitialProps入参对象
  • 如果需要注入pathname,query 或 asPath到你组件中,你可以使用withRouter

7.1 utils\axios.tsx #

utils\axios.tsx

import axios from 'axios';
axios.defaults.withCredentials = true
const instance = axios.create({
    baseURL: 'http://localhost:4000'
})
export default instance;

7.2 pages\user\add.tsx #

pages\user\add.tsx

import UserLayout from './index';
import router from 'next/router';
+import { Form, Input, Button, Icon, message } from 'antd';
+import axios from '../../utils/axios';
function UserAdd(props) {
+    async function handleSubmit(event) {
+        event.preventDefault();
+        let values = props.form.getFieldsValue();
+        let response = await axios.post('/api/register', values);
+        if (response.data.code === 0) {
+            router.push('/user/list');
+        } else {
+            message.error('添加用户失败');
+        }
+    }
    const { getFieldDecorator } = props.form;
    return (
        <UserLayout>
+            <Form onSubmit={handleSubmit} className="login-form" style={{ maxWidth: '300px' }}>
                {props.currentUser && <span>创建者:{props.currentUser.username}</span>}
                <Form.Item>
                    {getFieldDecorator('username', {
                        rules: [{ required: true, message: 'Please input your username!' }],
                    })(
                        <Input
                            prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
                            placeholder="Username"
                        />,
                    )}
                </Form.Item>
                <Form.Item>
                    {getFieldDecorator('password', {
                        rules: [{ required: true, message: 'Please input your Password!' }],
                    })(
                        <Input
                            prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                            type="password"
                            placeholder="Password"
                        />,
                    )}
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit" className="login-form-button">
                        添加用户
                </Button>
                </Form.Item>
            </Form>
        </UserLayout>
    )
}
export default Form.create({ name: 'UserAdd' })(UserAdd);

7.3 user\list.tsx #

pages\user\list.tsx

import UserLayout from './index';
import { List } from 'antd';
import Link from 'next/link';
+import axios from '../../utils/axios';
function UseList(props) {
    console.log('4.UseList.render', props);
    return (
        <UserLayout>
            <List
                header={<div>用户列表</div>}
                footer={<div>共计多少{props.list.length}个用户</div>}
                bordered
                dataSource={props.list}
                renderItem={(item: any) => (
                    <List.Item key={item._id}>
                        <Link as={`/user/detail/${item._id}`} href={{ pathname: `/user/detail`, query: { id: item._id } }}><a>{item.username}</a></Link>
                    </List.Item>
                )}
            />
        </UserLayout>
    )
}

UseList.getInitialProps = async (ctx) => {
    if (ctx.req) { ctx.req = 'req'; }
    if (ctx.res) { ctx.res = 'res'; }
    console.log('2.UseList.getInitialProps ctx', ctx);
+    let response = await axios({ url: '/api/users', method: 'GET' });
+    return { list: response.data.data };
}

export default UseList;

8.用户详情 #

8.1 知识点 #

  • 路由跳转传参数
  • 模块和组件懒加载
  • 自定义服务端路由

8.2 user\detail.tsx #

pages\user\detail.tsx

import React, { useState } from 'react';
import UserLayout from './';
import { withRouter } from 'next/router';
import { Button } from 'antd';
import axios from '../../utils/axios';
import dynamic from 'next/dynamic';
const UserInfo = dynamic(import('../../components/UserInfo'))

function UserDetail(props) {
  let [show, setShow] = useState(false);
  return (
    <UserLayout>
      <p>ID: {props.router.query.id}</p>
      <Button onClick={() => setShow(!show)}>显示/隐藏</Button>
      {
        show && <UserInfo user={props.user} />
      }
    </UserLayout>
  )
}
UserDetail.getInitialProps = async (ctx) => {
  let response = await axios({ url: `/api/users/${ctx.query.id}`, method: 'GET' });
  return { user: response.data.data };
}
export default withRouter(UserDetail);

8.2 components\UserInfo.tsx #

components\UserInfo.tsx

import { useState } from 'react';
import { Button } from 'antd';
function UserInfo(props) {
    let [created, setCreated] = useState(props.user.created);
    async function changeFormat() {
        let moment = await import('moment');
        setCreated(moment.default(props.user.created).fromNow());
    }
    return (
        <>
            <p>用户名:{props.user.username}</p>
            <p>密码:{props.user.password}</p>
            <p>创建时间:{created}<Button onClick={changeFormat}>切换为相对时间</Button></p>
        </>
    )
}
export default UserInfo;

8.3 client\index.js #

client\index.js

let Koa = require('koa');
let Router = require('koa-router');
const next = require('next');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev: true });
const handler = app.getRequestHandler();
app.prepare().then(() => {
    const server = new Koa();
    let router = new Router();
+    router.get('/user/detail/:id', async (ctx, next) => {
+        const id = ctx.params.id;
+        await handler(ctx.req, ctx.res, {
+            pathname: '/user/detail',
+            query: { id }
+        });
+        ctx.response = false;
+    });
    server.use(router.routes());
    server.use(async (ctx, next) => {
        await handler(ctx.req, ctx.res);
        ctx.response = false;
    });
    server.listen(3000, () => console.log('server started at port 3000'));
});

9.登录 #

9.1 pages\login.tsx #

import router from 'next/router';
import { Form, Input, Button, Icon, message } from 'antd';
import axios from '../utils/axios';
function Login(props) {
    const { getFieldDecorator } = props.form;
    async function handleSubmit(event) {
        event.preventDefault();
        let values = props.form.getFieldsValue();
        let response = await axios.post('/api/login', values);
        if (response.data.code === 0) {
            router.push('/');
        } else {
            message.error('登录失败');
        }
    }
    return (
        <Form onSubmit={handleSubmit} className="login-form" style={{ maxWidth: '300px',margin:'20px auto' }}>
            <Form.Item>
                {getFieldDecorator('username', {
                    rules: [{ required: true, message: 'Please input your username!' }],
                })(
                    <Input
                        prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
                        placeholder="Username"
                    />,
                )}
            </Form.Item>
            <Form.Item>
                {getFieldDecorator('password', {
                    rules: [{ required: true, message: 'Please input your Password!' }],
                })(
                    <Input
                        prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                        type="password"
                        placeholder="Password"
                    />,
                )}
            </Form.Item>
            <Form.Item>
                <Button type="primary" htmlType="submit" className="login-form-button">
                    登录
                </Button>
            </Form.Item>
        </Form>
    )
}
const WrappedLogin = Form.create({ name: 'Login' })(Login);
export default WrappedLogin;

10.集成redux #

10.1 安装依赖 #

yarn add redux react-redux

10.2 pages_app.tsx #

pages_app.tsx

import App from 'next/app';
import Link from 'next/link';
+import { Layout, Menu, Icon, Avatar } from 'antd';
import 'antd/dist/antd.css';
import { withRouter } from 'next/router';
+import axios from '../utils/axios';
+import initStore from '../store';
+import { Provider } from 'react-redux';
+import * as TYEPS from '../store/action-types';
+const { Header, Footer, Content } = Layout;
+declare global {
+    interface Window {
+        _redux_store_: any
+    }
+}
+function getStore(initialState) {
+    if (typeof window == 'undefined') {
+        return initStore(initialState);
+    } else {
+        if (!window._redux_store_) {
+            window._redux_store_ = initStore(initialState);
+        }
+        return window._redux_store_;
+    }
+}
class LayoutApp extends App<any> {
+    store: any
+    constructor(props) {
+        super(props);
+        this.store = getStore(props.initialState);
+    }
+    static async getInitialProps({ Component, ctx }) {
+        let store = getStore({});
+        let currentUser;
+        let options: any = { url: '/api/currentUser' };
+        if (ctx.req&&ctx.req.headers.cookie) {
+            (options.headers = options.headers || {}).cookie = ctx.req.headers.cookie;
+        }
+        let response = await axios(options);
+        if (response.data.code == 0) {
+            currentUser = response.data.data;
+            store.dispatch({ type: TYEPS.SET_USER_INFO, payload: currentUser });
+        }
        let pageProps = {};
        if (Component.getInitialProps)
            pageProps = await Component.getInitialProps(ctx);

+        return { pageProps, currentUser, initialState: store.getState() };
    }
    render() {
        let { Component } = this.props as any;
        let pathname = this.props.router.pathname;
        pathname = '/' + (pathname.split('/')[1]);
        return (
+            <Provider store={this.store}>
                <style jsx>
                    {`a{display:inline-block!important;}`}
                </style>
                <Layout>
                    <Header className="header">
                        <img src="/images/jglogo.png" style={{ width: 120, height: 31, margin: '16px 24px 16px 0px', float: 'left' }} />
                        <Menu theme="dark" mode="horizontal" style={{ lineHeight: '64px', display: 'inline-block' }}
                            selectedKeys={[pathname]}
                            defaultSelectedKeys={[pathname]}>
                            <Menu.Item key="/">
                                <Icon type="home" /><Link href="/"><a>首页</a></Link>
                            </Menu.Item>
                            <Menu.Item key="/user">
                                <Icon type="/user" /> <Link href="/user" ><a>用户管理</a></Link>
                            </Menu.Item>
                            <Menu.Item key="/profile">
                                <Icon type="profile" /><Link href="/profile"><a>个人中心</a></Link>
                            </Menu.Item>
                            <Menu.Item key="/login">
                                <Icon type="login" /><Link href="/login"><a>登录</a></Link>
                            </Menu.Item>
                        </Menu>
+                        {
+                            this.props.currentUser && <div style={{ display: 'inline-block', float: 'right', color: 'red' }}>
+                                <Avatar style={{ color: '#F00', backgroundColor: '#CCC' }}>{this.props.currentUser.username}</Avatar>
+                            </div>
+                        }
                    </Header>
                    <Component {...this.props.pageProps} />
                    <Footer style={{ textAlign: 'center' }} >@copyright 前端架构</Footer>
                </Layout>
+            </Provider>
        )
    }
}
export default withRouter(LayoutApp);

10.3 user\add.tsx #

pages\user\add.tsx

import UserLayout from './index';
import router from 'next/router';
import { Form, Input, Button, Icon, message } from 'antd';
import axios from '../../utils/axios';
+import { connect } from 'react-redux';
function UserAdd(props) {
    async function handleSubmit(event) {
        event.preventDefault();
        let values = props.form.getFieldsValue();
        let response = await axios.post('/api/register', values);
        if (response.data.code === 0) {
            router.push('/user/list');
        } else {
            message.error('添加用户失败');
        }
    }
    const { getFieldDecorator } = props.form;
    return (
        <UserLayout>
            <Form onSubmit={handleSubmit} className="login-form" style={{ maxWidth: '300px' }}>
                <Form.Item>
                    {getFieldDecorator('username', {
                        rules: [{ required: true, message: 'Please input your username!' }],
                    })(
                        <Input
                            prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
                            placeholder="Username"
                        />,
                    )}
                </Form.Item>
                <Form.Item>
                    {getFieldDecorator('password', {
                        rules: [{ required: true, message: 'Please input your Password!' }],
                    })(
                        <Input
                            prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                            type="password"
                            placeholder="Password"
                        />,
                    )}
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit" className="login-form-button">
                        添加用户
                </Button>
                </Form.Item>
            </Form>
        </UserLayout>
    )
}
+const WrappedUserAdd = Form.create({ name: 'UserAdd' })(UserAdd);
+export default WrappedUserAdd;

10.4 action-types.tsx #

store\action-types.tsx

export const SET_USER_INFO = 'SET_USER_INFO';//设置用户信息

10.5 store\index.tsx #

store\index.tsx

import { createStore } from 'redux';
import * as TYPES from './action-types';
let initState = {
    currentUser: null
}
const reducer = (state = initState, action) => {
    switch (action.type) {
        case TYPES.SET_USER_INFO:
            return { currentUser: action.payload }
        default:
            return state;
    }
}

export default function initStore(initialState) {
    const store = createStore(reducer, initialState);
    return store;
}

11.loading效果 #

  • 路由事件
事件 触发时机
routeChangeStart(url) 路由开始切换时触发
routeChangeComplete(url) 完成路由切换时触发
routeChangeError(err, url) 路由切换报错时触发
beforeHistoryChange(url) 浏览器 history 模式开始切换时触发
hashChangeStart(url) 开始切换 hash 值但是没有切换页面路由时触发
hashChangeComplete(url) 完成切换 hash 值但是没有切换页面路由时触发

11.1 pages_app.tsx #

import App from 'next/app';
import Link from 'next/link';
import { Layout, Menu, Icon, Avatar } from 'antd';
import 'antd/dist/antd.css';
import { withRouter } from 'next/router';
import axios from '../utils/axios';
import initStore from '../store';
import { Provider } from 'react-redux';
import * as TYEPS from '../store/action-types';
+import router from 'next/router';
+import { Spin } from 'antd';
const { Header, Footer, Content } = Layout;
declare global {
    interface Window {
        _redux_store_: any
    }
}
function getStore(initialState) {
    if (typeof window == 'undefined') {
        return initStore(initialState);
    } else {
        if (!window._redux_store_) {
            window._redux_store_ = initStore(initialState);
        }
        return window._redux_store_;
    }
}
class LayoutApp extends App<any> {
    store: any
+    state = { loading: false }
+    routeChangeStart: any
+    routeChangeComplete: any
    constructor(props) {
        super(props);
        this.store = getStore(props.initialState);
    }
    static async getInitialProps({ Component, ctx }) {
        let store = getStore({});
        let currentUser;
        let options: any = { url: '/api/currentUser' };
        if (ctx.req) {
            (options.headers = options.headers || {}).cookie = ctx.req.headers.cookie;
        }
        let response = await axios(options);
        if (response.data.code == 0) {
            currentUser = response.data.data;
            store.dispatch({ type: TYEPS.SET_USER_INFO, payload: currentUser });
        }
        let pageProps = {};
        if (Component.getInitialProps)
            pageProps = await Component.getInitialProps(ctx);

        return { pageProps, currentUser, initialState: store.getState() };
    }
+    componentDidMount() {
+        this.routeChangeStart = (url) => {
+            this.setState({ loading: true });
+        };
+        router.events.on('routeChangeStart', this.routeChangeStart);
+        this.routeChangeComplete = (url) => {
+            this.setState({ loading: false });
+        };
+        router.events.on('routeChangeComplete', this.routeChangeComplete);
+    }
    componentWillUnmount() {
        router.events.off('routeChangeStart', this.routeChangeStart)
        router.events.off('routeChangeStart', this.routeChangeComplete)
    }
    render() {
        let { Component, pageProps, currentUser } = this.props as any;
        let pathname = this.props.router.pathname;
        pathname = '/' + (pathname.split('/')[1]);
        return (
            <Provider store={this.store}>
                <style jsx>
                    {`a{display:inline-block!important;}`}
                </style>
                <Layout>
                    <Header className="header">
                        <img src="/images/jglogo.png" style={{ width: 120, height: 31, margin: '16px 24px 16px 0px', float: 'left' }} />
                        <Menu theme="dark" mode="horizontal" style={{ lineHeight: '64px', display: 'inline-block' }}
                            selectedKeys={[pathname]}
                            defaultSelectedKeys={[pathname]}>
                            <Menu.Item key="/">
                                <Icon type="home" /><Link href="/"><a>首页</a></Link>
                            </Menu.Item>
                            <Menu.Item key="/user">
                                <Icon type="/user" /> <Link href="/user" ><a>用户管理</a></Link>
                            </Menu.Item>
                            <Menu.Item key="/profile">
                                <Icon type="profile" /><Link href="/profile"><a>个人中心</a></Link>
                            </Menu.Item>
                            <Menu.Item key="/login">
                                <Icon type="login" /><Link href="/login"><a>登录</a></Link>
                            </Menu.Item>
                        </Menu>
+                        {
+                            this.props.currentUser && <div style={{ display: 'inline-block', float: 'right', color: 'red' }}>
+                                <Avatar style={{ color: '#F00', backgroundColor: '#CCC' }}>{this.props.currentUser.username}</Avatar>
+                            </div>
                        }
                    </Header>
                    {
                        this.state.loading ? <Spin style={{ margin: '50px auto' }} /> : <Component {...pageProps} currentUser={currentUser} />
                    }
                    <Footer style={{ textAlign: 'center' }} >@copyright 前端架构</Footer>
                </Layout>
            </Provider>
        )
    }
}
export default withRouter(LayoutApp);

12.受保护路由 #

12.1 pages\profile.tsx #

pages\profile.tsx

import router from 'next/router';
import { Button, Layout } from 'antd';
+import axios from '../utils/axios';
const { Content } = Layout;
+function Profile(props) {
    return (
        <Content style={{ margin: '20px auto' }}>
+           <div>当前登录用户:{props.currentUser.username}</div>
            <Button onClick={() => router.back()}>返回</Button>
        </Content>
    )
}
+Profile.getInitialProps = async function (ctx) {
+    let options: any = { url: '/api/currentUser' };
+    if (ctx.req&&ctx.req.headers.cookie) {
+        (options.headers = options.headers || {}).cookie = ctx.req.headers.cookie;
+    }
+    let response = await axios(options);
+    if (response.data.code == 0) {
+        return {};
+    } else {
+        if (ctx.req) {
+            ctx.res.writeHead(303, { Location: '/login' })
+            ctx.res.end()
+        } else {
+            router.push('/login');
+        }
+        return {};
+    }
+}
+
+const WrappedProfile = connect(
+    state => state
+)(Profile);
+export default WrappedProfile;

13.自定义Document #

13.1 pages_document.js #

pages_document.js

import Document, { Html, Head, Main, NextScript } from 'next/document';
class CustomDocument extends Document {
    static async getInitialProps(ctx) {
        const props = await Document.getInitialProps(ctx);
        return { ...props };
    }
    render() {
        return (
            <Html>
                <Head>
                    <style>
                        {
                            `
                            *{
                                padding:0;
                                margin:0;
                            }
                            `
                        }
                    </style>
                </Head>
                <body>
                    <Main />
                    <NextScript />
                </body>
            </Html>
        )
    }
}
export default CustomDocument;

13.2 pages\index.tsx #

pages\index.tsx

import router from 'next/router'
import { Button, Layout } from 'antd';
import Head from 'next/head'
const { Content } = Layout;
export default function () {
    return (
        <>
            <Head>
                <title>首页</title>
                <meta name="description" content="这是首页" />
            </Head>
            <Content style={{ margin: '20px auto' }}>
                <div>Home</div>
                <Button onClick={() => router.push('/user')}>/user</Button>
            </Content>
        </>
    )
}

14.服务端 #

yarn add express  body-parser  cors express-session connect-mongo mongoose

14.1 api\index.js #

let express = require("express");
let bodyParser = require("body-parser");
let cors = require("cors");
let Models = require('./db');
let session = require("express-session");
let config = require('./config');
let MongoStore = require('connect-mongo')(session);
let app = express();
app.use(
    cors({
        origin: ['http://localhost:3000'],
        credentials: true,
        allowedHeaders: "Content-Type,Authorization",
        methods: "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS"
    })
);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(
    session({
        secret: config.secret,
        resave: false,
        saveUninitialized: true,
        store: new MongoStore({
            url: config.dbUrl,
            mongoOptions: {
                useNewUrlParser: true,
                useUnifiedTopology: true
            }
        })
    })
);
app.get('/api/users', async (req, res) => {
    let users = await Models.UserModel.find();
    res.send({ code: 0, data: users });
});
app.get('/api/users/:id', async (req, res) => {
    let user = await Models.UserModel.findById(req.params.id);
    res.send({ code: 0, data: user });
});
app.post('/api/register', async (req, res) => {
    let user = req.body;
    user = await Models.UserModel.create(user);
    res.send({ code: 0, data: user });
});
app.post('/api/login', async (req, res) => {
    let user = req.body;
    let dbUser = await Models.UserModel.findOne(user);
    if (dbUser) {
        req.session.currentUser = dbUser;
        res.send({ code: 0, data: dbUser });
    } else {
        res.send({ code: 1, error: '登录失败' });
    }
});

app.get('/api/currentUser', async (req, res) => {
    let currentUser = req.session.currentUser;
    if (currentUser) {
        res.send({ code: 0, data: currentUser });
    } else {
        res.send({ code: 1, error: '当前用户未登录' });
    }
});
app.listen(4000, () => {
    console.log('服务器在4000端口启动!');
});

14.2 api\config.js #

api\config.js

module.exports = {
    secret: 'zhufeng',
    dbUrl: "mongodb://127.0.0.1/zhufengnext2"
}

14.3 api\db.js #

api\db.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ObjectId = Schema.Types.ObjectId;
const config = require('./config');
const conn = mongoose.createConnection(config.dbUrl, { useNewUrlParser: true, useUnifiedTopology: true });
const UserModel = conn.model('User', new Schema({
    username: { type: String },
    password: { type: String }
}, { timestamps: { createdAt: 'created', updatedAt: 'updated' } }));

module.exports = {
    UserModel
}

访问验证

请输入访问令牌

Token不正确,请重新输入