React+Ant Design 4.4.1登录及路由导航

package.json:

{
  "name": "antd-demo",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@ant-design/icons": "^4.2.1",
    "@babel/core": "7.9.0",
    "@svgr/webpack": "4.3.3",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "@typescript-eslint/eslint-plugin": "^2.10.0",
    "@typescript-eslint/parser": "^2.10.0",
    "antd": "^4.7.0",
    "axios": "^0.19.2",
    "babel-eslint": "10.1.0",
    "babel-jest": "^24.9.0",
    "babel-loader": "8.1.0",
    "babel-plugin-import": "^1.13.0",
    "babel-plugin-named-asset-import": "^0.3.6",
    "babel-preset-react-app": "^9.1.2",
    "camelcase": "^5.3.1",
    "case-sensitive-paths-webpack-plugin": "2.3.0",
    "css-loader": "3.4.2",
    "dotenv": "8.2.0",
    "dotenv-expand": "5.1.0",
    "echarts": "^4.9.0",
    "echarts-for-react": "^2.0.16",
    "eslint": "^6.6.0",
    "eslint-config-react-app": "^5.2.1",
    "eslint-loader": "3.0.3",
    "eslint-plugin-flowtype": "4.6.0",
    "eslint-plugin-import": "2.20.1",
    "eslint-plugin-jsx-a11y": "6.2.3",
    "eslint-plugin-react": "7.19.0",
    "eslint-plugin-react-hooks": "^1.6.1",
    "file-loader": "4.3.0",
    "fs-extra": "^8.1.0",
    "html-webpack-plugin": "4.0.0-beta.11",
    "identity-obj-proxy": "3.0.0",
    "jest": "24.9.0",
    "jest-environment-jsdom-fourteen": "1.0.1",
    "jest-resolve": "24.9.0",
    "jest-watch-typeahead": "0.4.2",
    "mini-css-extract-plugin": "0.9.0",
    "optimize-css-assets-webpack-plugin": "5.0.3",
    "pnp-webpack-plugin": "1.6.4",
    "postcss-flexbugs-fixes": "4.1.0",
    "postcss-loader": "3.0.0",
    "postcss-normalize": "8.0.1",
    "postcss-preset-env": "6.7.0",
    "postcss-safe-parser": "4.0.1",
    "react": "^16.13.1",
    "react-app-polyfill": "^1.0.6",
    "react-dev-utils": "^10.2.1",
    "react-dom": "^16.13.1",
    "react-router": "^4.2.0",
    "react-router-dom": "^4.2.0",
    "react-transition-group": "^4.4.1",
    "redux": "^4.0.5",
    "resolve": "1.15.0",
    "resolve-url-loader": "3.1.1",
    "sass-loader": "8.0.2",
    "semver": "6.3.0",
    "style-loader": "0.23.1",
    "terser-webpack-plugin": "2.3.5",
    "ts-pnp": "1.1.6",
    "url-loader": "2.3.0",
    "webpack": "4.42.0",
    "webpack-dev-server": "3.10.3",
    "webpack-manifest-plugin": "2.2.0",
    "workbox-webpack-plugin": "4.3.1"
  },
  "scripts": {
    "start": "node scripts/start.js",
    "build": "node scripts/build.js",
    "test": "node scripts/test.js"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "proxy": "http://localhost:9999",
  "homepage": ".",
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "jest": {
    "roots": [
      "/src"
    ],
    "collectCoverageFrom": [
      "src/**/*.{js,jsx,ts,tsx}",
      "!src/**/*.d.ts"
    ],
    "setupFiles": [
      "react-app-polyfill/jsdom"
    ],
    "setupFilesAfterEnv": [
      "/src/setupTests.js"
    ],
    "testMatch": [
      "/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
      "/src/**/*.{spec,test}.{js,jsx,ts,tsx}"
    ],
    "testEnvironment": "jest-environment-jsdom-fourteen",
    "transform": {
      "^.+\\.(js|jsx|ts|tsx)$": "/node_modules/babel-jest",
      "^.+\\.css$": "/config/jest/cssTransform.js",
      "^(?!.*\\.(js|jsx|ts|tsx|css|json)$)": "/config/jest/fileTransform.js"
    },
    "transformIgnorePatterns": [
      "[/\\\\]node_modules[/\\\\].+\\.(js|jsx|ts|tsx)$",
      "^.+\\.module\\.(css|sass|scss)$"
    ],
    "modulePaths": [],
    "moduleNameMapper": {
      "^react-native$": "react-native-web",
      "^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy"
    },
    "moduleFileExtensions": [
      "web.js",
      "js",
      "web.ts",
      "ts",
      "web.tsx",
      "tsx",
      "json",
      "web.jsx",
      "jsx",
      "node"
    ],
    "watchPlugins": [
      "jest-watch-typeahead/filename",
      "jest-watch-typeahead/testname"
    ]
  },
  "devDependencies": {
    "less": "^3.12.2",
    "less-loader": "^6.2.0"
  }
}

App.js:

import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom'
import Login from './pages/login/login';
import Admin from './pages/admin/admin';

class App extends React.Component {
  render() {
    return (
      
        
        
      
    )
  }
}

export default App;

login.jsx:

import React, { Component } from 'react'
import './login.less'
import { Form, Input, Button, notification } from 'antd';
import { UserOutlined, KeyOutlined } from '@ant-design/icons';
import $http from '../../ajax/http.js'

const layout = {
    labelCol: {
        span: 0,
    },
    wrapperCol: {
        span: 24,
    }
};

const tailLayout = {
    wrapperCol: { offset: 0, span: 24 },
};

export default class Login extends Component {
    // 表单相关
    formRef = React.createRef(); // 定义一个表单

    onFinish = values => {
        $http({
          method: "POST",
          url: "/article/check_login_status/",
          data: JSON.stringify(values)
        })
        .then(res => {
            localStorage['token'] = 1;
            this.props.history.replace("/");
        })
        .catch(err => {
            notification["error"]({
                message: '错误提示',
                description:
                  '用户名或密码错误',
            });
        });
    }

    onFinishFailed = errorInfo => {
        notification["error"]({
            message: '错误提示',
            description:
              '用户名或密码错误',
        });
    }

    render() {
        return (
            
{/* logo

React App管理系统

*/}

React App管理系统

} /> } />
) } }

admin.jsx(后台框架页):

import React, { Component } from 'react'
import { Layout } from 'antd'
import { Route, Redirect, Switch } from 'react-router-dom'
import LeftNav from '../../components/left-nav/'
import HeaderCom from '../../components/header/'
import HomeCom from '../home/home'
import MonitorCom from '../home/monitor.jsx'
import WorkbenchCom from '../home/workbench.jsx'
import LineCom from '../charts/line'
import BarCom from '../charts/bar'
import PieCom from '../charts/pie'
import FormCom from '../data-input/form'
import TableCom from '../data-show/table'
import TabsCom from '../data-show/tabs'
import CardCom from '../data-show/card'
import TimelineCom from '../data-show/timeline'
import DescriptionsCom from '../data-show/descriptions'
import EmptyCom from '../data-show/empty'
import NotificationCom from '../feedback/notification'
import ModalCom from '../feedback/modal'
import ResultCom from '../feedback/result'
import Com403 from '../abnormal/403'
import Com404 from '../abnormal/404'
import Com500 from '../abnormal/500'
import BaseForm from '../form/base-form'
import ModalForm from '../form/modal-form'
import StepForm from '../form/step-form'
import AdvancedForm from '../form/advanced-form'
import SearchList from '../list/search-list'
import QueryTable from '../list/query-table'
import StandardList from '../list/standard-list'
import CardList from '../list/card-list'
import TreeList from '../list/tree-list'
import baseDetail from '../detail/base-detail'
import seniorDetail from '../detail/senior-detail'
import Administrator from '../webdisk/administrator'
import Log from '../webdisk/log'
import Myshare from '../webdisk/myshare'
import Usbkey from '../webdisk/usbkey'
import Baseinfo from '../firmstor/baseinfo'
import FileRecovery from '../firmstor/file-recovery'
import './admin.less'

const { Content, Sider } = Layout;

export default class Admin extends Component {
    state = {
        collapsed: false
    };

    // 控制菜单左右缩放
    onCollapse = collapsed => {
        this.setState({ collapsed });
    };

    render() {
        if (Number(localStorage['token']) === 0) {
            // 自动跳转到登陆(在render()中)
            return ;
        }

        // const loginOut = e => {
        //     e.preventDefault();
        //     localStorage['token'] = 0;
        //     this.props.history.replace("/login"); // this.props.history.replace("/login")写到render之外会有问题,此时组件需要用withRouter包装
        // }

        return (
            
                
                
                    {/*collapsible、collapsed、onCollapse:控制整个菜单的左右收缩*/}
                    
                        
                    
                    
                        
                            
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                            
                        
                    
                
            
        )
    }
}

home.jsx(首页):

import React, { Component } from 'react'
import { Table, Pagination, Card, Modal, Button, Form, Input, InputNumber, Select, Checkbox, Radio, notification } from 'antd'
import { PlusOutlined } from '@ant-design/icons';
import ReactEcharts from 'echarts-for-react'
import axios from 'axios'

const { Option } = Select;
const { TextArea } = Input;

const layout = {
    labelCol: {
        span: 5,
    },
    wrapperCol: {
        span: 19,
    }
};

export default class Home extends Component {
    state = {
        chartData: [
            ['2019-10-10', 200],
            ['2019-10-11', 400],
            ['2019-10-12', 650],
            ['2019-10-13', 500],
            ['2019-10-14', 250],
            ['2019-10-15', 300],
            ['2019-10-16', 450],
            ['2019-10-17', 300],
            ['2019-10-18', 200]
        ],
        selectedRowKeys: [], // 表格选择项Keys
        selectedRows: [], // 表格选择项Rows
        tableData: [],
        total: 0, // for Pagination
        columns: [
            {
                title: 'ID',
                dataIndex: 'id',
                width: 30,
            },
            {
                title: '标题',
                dataIndex: 'title',
                width: 500,
            },
            {
                title: '内容',
                dataIndex: 'content'
            },
        ],
        addModalVisible: false
    };

    getSalesVolumeChartData = (chartData) => {
        return {
            grid: {
                left: '3%',
                right: '3%',
                bottom: '3%',
                top: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false
            },
            yAxis: {
                type: 'value',
                boundaryGap: [0, '30%']
            },
            visualMap: {
                type: 'piecewise',
                show: false,
                dimension: 0,
                seriesIndex: 0,
                pieces: [{
                    gt: 1,
                    lt: 3,
                    color: 'rgba(0, 180, 0, 0.5)'
                }, {
                    gt: 5,
                    lt: 7,
                    color: 'rgba(0, 180, 0, 0.5)'
                }]
            },
            series: [
                {
                    type: 'line',
                    smooth: 0.6,
                    symbol: 'none',
                    lineStyle: {
                        color: 'green',
                        width: 5
                    },
                    markLine: {
                        symbol: ['none', 'none'],
                        label: { show: false },
                        data: [
                            { xAxis: 1 },
                            { xAxis: 3 },
                            { xAxis: 5 },
                            { xAxis: 7 }
                        ]
                    },
                    areaStyle: {},
                    data: chartData
                }
            ]
        };
    }

    onTableSelectChange = (selectedRowKeys, selectedRows) => {
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        console.log('selectedRows changed: ', selectedRows);
        this.setState({ selectedRowKeys, selectedRows });
    };

    onSelectChange = selectedRowKeys => {
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        this.setState({ selectedRowKeys });
    };

    /**
     * 表格
     */

    // 获取表格数据
    getData(pageNumber, pageSize) {
        axios.get(`/article/all/?pageSize=${pageSize}&pageNumber=${pageNumber}&sortName=id&sortOrder=desc&_=1595230808893`).then((resp) => {
            let ajaxData = [];
            for (let i = 0; i < resp.data.rows.length; i++) {
                ajaxData.push({
                    key: resp.data.rows[i].id,
                    id: resp.data.rows[i].id,
                    title: resp.data.rows[i].title,
                    content: resp.data.rows[i].content,
                });
            }

            this.setState({
                tableData: ajaxData,
                total: resp.data.total
            })

        }, (err) => {
            console.log(err);
        });
    }

    onChange = (pageNumber, pageSize) => {
        this.pageNum = pageNumber;
        this.getData(pageNumber, pageSize);
    };

    /**
     * 添加modal
     */

    // for modal
    showAddModal = () => {
        this.setState({
            addModalVisible: true
        })
    }

    addModalHandleOk = e => {
        this.addModalFormRef.current.validateFields()
            .then(values => {
                this.addModalFormRef.current.resetFields();
                this.setState({
                    addModalVisible: false
                });
            })
            .catch(info => {
                console.log('Validate Failed:', info);
            });
    }

    addModalHandCancel = e => {
        this.addModalFormRef.current.resetFields();
        this.setState({
            addModalVisible: false
        })
    }

    // 表单相关
    addModalFormRef = React.createRef(); // 定义一个表单

    /**
     * 钩子函数
     */

    componentDidMount() {
        this.getData(1, 5);

        setInterval(() => {
            let chartData1 = Math.ceil(Math.random() * 100);
            let chartData2 = Math.ceil(Math.random() * 100);
            let chartData3 = Math.ceil(Math.random() * 100);
            let chartData4 = Math.ceil(Math.random() * 100);
            let chartData5 = Math.ceil(Math.random() * 100);
            let chartData6 = Math.ceil(Math.random() * 100);
            let chartData7 = Math.ceil(Math.random() * 100);
            let chartData8 = Math.ceil(Math.random() * 100);
            let chartData9 = Math.ceil(Math.random() * 100);
            let chartData = [
                ['2019-10-10', chartData1],
                ['2019-10-11', chartData2],
                ['2019-10-12', chartData3],
                ['2019-10-13', chartData4],
                ['2019-10-14', chartData5],
                ['2019-10-15', chartData6],
                ['2019-10-16', chartData7],
                ['2019-10-17', chartData8],
                ['2019-10-18', chartData9]
            ];

            this.setState({ chartData });
        }, 1000)
    }

    render() {
        // 控制表格选择
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: this.onTableSelectChange
        };

        return (<>
            
                
            

            
} onClick={this.showAddModal}>添加} style={{ width: '100%' }}> { return { onClick: event => { console.log(record) }, // 点击行 onDoubleClick: event => { }, onContextMenu: event => { }, onMouseEnter: event => { }, // 鼠标移入行 onMouseLeave: event => { }, }; }} rowSelection={rowSelection} columns={this.state.columns} dataSource={this.state.tableData} pagination={{ current: this.pageNum, total: this.state.total, pageSizeOptions: [5, 10, 20, 50, 100], defaultPageSize: 5, showSizeChanger: true, showQuickJumper: true, showTotal: (total, range) => `共 ${total} 条`, onChange: this.onChange }} bordered >
USBKEY G G