1. Install the dva – cli

  • npm install dva-cli -g

2. Create an application

dva new dvadashboard

  [Dvadashboard is the project name]

3. Install mockjs

  • npm install mockjs –save

4. Configuration mockjs

  • Open. Roadhogrc.mock. js as follows

  

const fs=require('fs');
const path=require('path');
const mockPath=path.join(__dirname+'/mock');

const mock={};
fs.readdirSync(mockPath).forEach(file=>{

    Object.assign(mock,require('./mock/'+file));
});

module.exports=mock;Copy the code

5. Simulate the user management API

Create user.js in the mock folder

  

API Settings:

There are only two apis simulated here: 1. Get all user data; 2. Add users

const Mock=require('mockjs');

let db=Mock.mock({
    'data|3-6':[{
        id:'@id',
        name:'@name'.'age|18-32': 1}}); module.exports={ [`GET /api/users`](req,res){ res.status(200).json(db); }, [`POST /api/users`](req,res){let user=req.body;
        console.log(req);
        user.id=Mock.mock('@id'); db.data.push(user); res.status(200).json(user); }}Copy the code

To see if the API is available, go to the project directory and execute NPM start

Enter the default page. Default port 8000 The following is the default page after the project is started

To access the API http://localhost:8000/api/users ok, have access to a list of successful return to simulate a user data

  

6. Install antd

  

  • npm install antd babel-plugin-import --save

  

Babel-plugin-import is used to load ANTD scripts and styles on demand

After installation is complete, the configuration is modified using ANTD. Roadhogrc file

Add [“import”,{“libraryName”:”antd”,”style”:” CSS “}] the final file looks like this:

  

{
  "entry": "src/index.js"."env": {
    "development": {
      "extraBabelPlugins": [
        "dva-hmr"."transform-runtime"["import", {"libraryName":"antd"."style":"css"}}]]."production": {
      "extraBabelPlugins": [
        "transform-runtime"["import", {"libraryName":"antd"."style":"css"}]}}Copy the code

  

7. Define routes

  • Create userspage.js in the SRC /routes/ folder

This is probably the simplest page out there

import { connect } from 'dva';

const UserPage=()=>{

    return (
        <div>
            <h1>UserPage</h1>
        </div>
    );
};

export default connect()(UserPage);Copy the code

  • Modify the SRC /router.js file to register routing information

A component dynamic loading was added

import React from 'react';
import { Router, Route, Switch } from 'dva/router';
import dynamic from 'dva/dynamic';
import IndexPage from './routes/IndexPage';

function RouterConfig({ history,app }) {

  const UserPage=dynamic({
    app,
    
    component:()=>import('./routes/usersPage')});return (
    <Router history= {history}>
      <Switch>
        <Route path="/" exact component={IndexPage} />
        <Route path="/users" exact component={UserPage} />
      </Switch>
    </Router>
  );
}

export default RouterConfig;Copy the code

To view the route configuration, visit http://localhost:8000/#/users

I’m showing the content

8. Add communication with the server

  • Modify SRC /utils/request.js as follows to provide basic Ajax data access

  

There are also many specific advantages and disadvantages of using AXIo that have not been studied.

  

import fetch from 'dva/fetch';

const checkStatus=(response)=>{

    if(response.status>=200 && response.status<=200){

      return response;
    }

    const error=new Error(response.statusText);
    error.response=response;
    throw error;
};

export default async function request(url,options={}) {
    
    options.headers={
        'Content-Type':'application/json'
    }
    const response=await fetch(url,options);
    checkStatus(response);
    const data=await response.json();

    return data;
}Copy the code

User. Service (which encapsulates basic Ajax communication and provides a business interface) calls the request method directly in the business layer.

  • Then create user.js under SRC /models
import request from '.. /utils/request';
const User={
    namespace:"user",

    state:{
        list:[],
        visibleModal:false
    },
    reducers:{
        save(state,{ payload:{ data:list } }){

            return {
                ...state,
                list
            };
        }
    },
    effects:{
        * query({},{ call,put }){
            const { data }=yield call(request,'/api/users',{ method:'GET' });
            yield put({type:'save',payload:{ data }});
        },
        * create({ payload:{ user } },{ call,put }){
            yield call(request,'/api/users',{ 
                body:JSON.stringify(user),
                method:'POST'
            });
            yield put({type:'query',payload:{  }});
        }
    }, 
    subscriptions:{
        setup({ dispatch,history }){

            console.log('running subscriptions ... ');
            return history.listen(({ pathname,search })=>{

                console.log(`pathname: ${pathname}`);
                dispatch({ type:'query'}); }); }}};export default User;Copy the code

Dva’s encapsulation of Redux React-Saga is shown here

  • Then register model to change the routing code to:
import React from 'react';
import { Router, Route, Switch } from 'dva/router';
import dynamic from 'dva/dynamic';
import IndexPage from './routes/IndexPage';

function RouterConfig({ history,app }) {

  const UserPage=dynamic({
    app,
    models:()=>[
      import('./models/user')
    ],
    component:()=>import('./routes/usersPage')});return (
    <Router history= {history}>
      <Switch>
        <Route path="/" exact component={IndexPage} />
        <Route path="/users" exact component={UserPage} />
      </Switch>
    </Router>
  );
}

export default RouterConfig;Copy the code

9. The new user data list component is carried by Tabel of ANTD

Let’s also create the form for adding users

user.js

import { Table,Button } from 'antd';
import { connect } from 'dva';
import UserModal from './create';

const UserTable = ({ list,dispatch }) => {

    const createUser=(user)=>{
        dispatch({
            type:'user/create',
            payload:{
                user
            }
        });
    };

    const columns=[
        {
            Title:'ID',
            dataIndex:'id'
        },
        {
            Title:'NAME',
            dataIndex:'name'
        },
        {
            Title:'AGE',
            dataIndex:'age'}];return (
        <div>
            <UserModal record={ {} } ok={ createUser }>
                <Button type="primary">NEW</Button>
            </UserModal>
            <Table
                columns={ columns }
                dataSource={ list }
                rowKey={ t=>t.id }
                pagination={ false }>
                {/* users datatable */}
            </Table>
        </div>
    );
};

export default connect(({ user }) => {

    console.log(user);
    return {
        list: user.list
    };
})(UserTable);Copy the code

create.js

import React,{ Component } from 'react';
import { Modal,Form,Input } from 'antd';

class UserModal extends Component{
    constructor(props){
        super(props);
        this.state={
            visible:false
        };
    }

    
    render(){
        const { children,form:{ getFieldDecorator },record,ok }=this.props;

        const showModal=()=>{

            this.setState({
                visible:true
            });
        };
        const hideModal=()=>{

            this.setState({
                visible:false
            });
        };
        const save=()=>{

            this.props.form.validateFields((err,val)=>{
                //val ==> record

                // console.log(val);
                ok(val);
                hideModal();
            });
        };

        return (
            <div>
                <span onClick={ showModal }>
                    { children }
                </span>
                <Modal
                    title="Create User"
                    visible={ this.state.visible }
                    onCancel={ hideModal }
                    onOk={ save }>
                    <Form>
                        <Form.Item label="Name">
                            {
                                getFieldDecorator('name', {
                                    initialValue: record.name
                                })(<Input />)
                            }
                        </Form.Item>
                        <Form.Item>
                            {
                                getFieldDecorator('age',{
                                    initialValue:record.age
                                })(<Input />)
                            }
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        );
    };
}


export default Form.create()(UserModal);Copy the code

usersPage.js

import { connect } from 'dva';
import Main from '.. /components/layout/main';
import UserTable from '.. /components/user/user';

const UserPage=()=>{

    return (
        <Main>
            <h1>UserPage</h1>
            <UserTable />
        </Main>
    );
};

export default connect()(UserPage);Copy the code

10. Effect demonstration

11. Download source code

Or https://pan.baidu.com/s/1bo1R7o7