当前位置: 首页 > 编程日记 > 正文

dva + antd + mockjs 实现用户管理

1.安装dva-cli

  • npm install dva-cli -g

2.创建应用

  dva new dvadashboard  

  [dvadashboard为项目名]

     

3.安装mockjs

  •   npm install mockjs --save

4.配置mockjs

  •   打开.roadhogrc.mock.js 设置如下

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;

5.模拟用户管理API

  mock文件夹下新建user.js

  

API设置:

这里只模拟俩个api  1.获取所有用户数据  2.添加用户


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);}
}

接下来看一下api能不能使用, 进入项目目录, 执行 npm start 启动

进入默认页面  默认端口号 8000  如下是项目启动后默认页面

访问下api   http://localhost:8000/api/users     好了,可以访问  成功返回模拟用户列表数据

6.安装antd 

  

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

babel-plugin-import 是用来按需加载 antd 的脚本和样式的

安装完成后,配置使用antd  修改.roadhogrc文件

添加 ["import",{ "libraryName":"antd","style":"css" }]   最后文件如下所示:


{"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" }]]}}
}

7.定义路由

  •   在src/routes/ 文件夹下新建 usersPage.js

  这可能是最简单的一个页面了


import { connect } from 'dva';const UserPage=()=>{return (<div><h1>UserPage</h1></div>);
};export default connect()(UserPage);

  • 注册路由信息  修改src/router.js文件

顺手加了个组件动态加载


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;

查看一下路由配置效果  访问http://localhost:8000/#/users

显示内容了

8.添加与服务端通讯

  •   修改src/utils/request.js如下  用于提供基础的ajax数据访问

  也有不少使用axio的 具体优缺点还没研究。


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;
}

这里为了理解简单  省略一层 user.service (封装基础ajax通讯 提供业务接口)  在业务层中直接调用request里方法 【只是为了学习方便】

  • 然后在src/models下新建user.js

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;

这里主要体现dva对redux react-saga的封装处理  一目了然了

  • 然后注册model  修改路由处代码为:


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;

9.新建用户数据列表组件 使用antd的Tabel承载

  顺手也把添加用户的表单建了吧

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><Tablecolumns={ 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);

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><Modaltitle="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);

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);

10.效果演示

 11.源码下载 

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




原文发布时间为:2017年12月21日
原文作者: gaojinbo010 

本文来源:开源中国 如需转载请联系原作者







相关文章:

用S60操作系统SDK开发NOKIA手机应用程序(4)- 界面层框架及一些特性

Uikon和Avkon Series 60 将一个用户界面层(Avkon)添加在Symbian OS v7.0s 底层的Uikon 之上。Uikon是Symbian 核心用户界面&#xff0c;Avkon是S60平台的用户界面。Avkon 提供了一 套UI 组件和一个专为Series 60 设备设计的软件框架。UIKON 是所有Symbian OS设备都支持的一种用…

VS2010 发布web项目 问题

载&#xff1a;http://www.cnblogs.com/shaocm/archive/2012/08/10/2632116.html 转载于:https://www.cnblogs.com/zcttxs/p/3507007.html

软件生命周期中出现的文档名称(cont.)

需求相关&#xff1a;需求规格说明书 测试相关&#xff1a;测试计划书&#xff0c;测试报告

转:45 Useful JavaScript Tips, Tricks and Best Practices

原文来自于&#xff1a;http://flippinawesome.org/2013/12/23/45-useful-javascript-tips-tricks-and-best-practices/ 1 – Don’t forget var keyword when assigning a variable’s value for the first time. Assignment to an undeclared variable automatically results…

聊聊spring cloud gateway的PreserveHostHeaderGatewayFilter

序 本文主要研究下spring cloud gateway的PreserveHostHeaderGatewayFilter GatewayAutoConfiguration spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/config/GatewayAutoConfiguration.java Configuration ConditionalOnProperty(name…

静态测试与测试计划

文章目录1 静态测试2 评审2.1 what2.2 why2.3 形式2.4 分类2.4.1 属于软件测试的部分2.4.2 属于软件质量保证的部分&#xff1a;3 需求测试3.1 why3.2 需求中可能存在的问题3.3 需求文档检查要点3.3.1 完整性3.3.2 正确性3.3.3 一致性3.3.4 可行性3.3.5 无二义型3.3.6 健壮性3.…

中国HBase技术社区第一届Meetup资料大合集

2018年6月6号&#xff0c;由中国HBase技术社区组织&#xff0c;阿里云主办的中国第一次HBase Meetup在北京望京阿里中心举行&#xff0c;来自阿里、小米、滴滴、360等公司的各位HBase的PMC、committer共聚一堂&#xff0c;共同探讨HBase2.0的技术革新以及HBase在国内各个大型企…

寻找历史!!!

“你一点都不了解中国”。在大约四年的时间里&#xff0c;我几乎每天都听到类似的批 评。每周一的中午&#xff0c;我坐着红色的出租车沿着三环路前往上班地点。尽管北京拥有 世界上最宽阔的道路&#xff0c;但在早晨与傍晚时&#xff0c;那些亨利福特&#xff34;型车的后代们…

wikioi 1083 Cantor表

找规律题 现代数学的著名证明之一是Georg Cantor证明了有理数是可枚举的。他是用下面这一张表来证明这一命题的&#xff1a; 1/1 1/2 1/3 1/4 1/5 … 2/1 2/2 2/3 2/4 … 3/1 3/2 3/3 … 4/1 4/2 … 5/1 … … 我们以Z字形给上表的每一项编号。第一项是1/1&#xff0c;然后是1/…

hung-yi lee_p3_线性回归

文章目录本节目的解决过程损失函数解损失函数&#xff08;by梯度下降&#xff09;改进模型矫枉过正解决方案本课结论本节目的 找到这样一个函数&#xff0c;输入宝可梦当前的CP(Combat Point)值&#xff0c;得到它进化后的CP值。 解决过程 损失函数 函数的函数&#xff1a;衡…

PHP简单封装MysqlHelper类

MysqlHelper.class.php 1: <?php 2: 3: /** 4: * Mysql数据帮助类 5: */ 6: class MysqlHelper 7: { 8: function __construct() 9: { 10: if(isset($conn)){return;} 11: //创建连接对象 12: $this->connmysql_connect($this->…

python之XML文件解析

python对XML的解析 常见的XML编程接口有DOM和SAX&#xff0c;这两种接口处理XML文件的方式不同&#xff0c;当然使用场合也不同。 python有三种方法解析XML&#xff0c;分别是SAX&#xff0c;DOM&#xff0c;以及ElementTree三种方法。 以下案例依次介绍三种方法&#xff1a; 先…

这句话真他妈经典

研究解决一个问题的时候&#xff0c;通常花百分之二十的时间和精力&#xff0c;就能抓住问题的百分之八十&#xff0c;而为了完善那余下的百分之二十&#xff0c;却往往要花百分之八十的时间和精力 这句话真他妈经典&#xff0c;呵呵 转载于:https://www.cnblogs.com/webcool…

hung-yi lee_p4_Bias And Variance

文章目录本节目的biasvariance结论&#xff08;鱼和熊掌不可得兼&#xff09;如何解决减小bias的方案减小variance的方案对训练集进行处理得到更好的模型本节目的 where does the error come from?&#xff08;为什么最复杂的模型反而Loss函数的值越大&#xff09; error有…

感觉 Data Access Application Block(DAAB) 里也有可能写得不太好的地方

昨天下载了博客园的代码&#xff0c;里面有一个Data\SqlServer.cs我不清楚是不是 MS DAAB 里的原样文件。不过前面有声明如下&#xff1a;////Microsoft Data Access Application Block for .NET 3.0////SqlServer.cs////This file contains the implementations of the AdoHel…

微软压力测试工具 web application stress

WEB服务器的压力测试工具~ 115808 2009年8月1日lbimba 铜牌会员 这里给广大的煤油推荐一个web网站压力测试工具。它可以用来模拟多个用户操作网站&#xff0c;在程序投入运行时&#xff0c;可以用它来进行程序的测试并得到Web站点的稳定 参数&#xff0c;甚至于可以对一台小型的…

Didn't find class net.oschina.app.AppContext on

原因 你引入的Lib 未打钩 然后在 菜单Project -> Properties -> Java Build Path -> Order & Export, 然后选中你未打钩的, 然后菜单 Project->Clean&#xff0c;然后运行程序即可。转载于:https://blog.51cto.com/12237592/2129523

hung-yi lee_p5-7_Gradient Descent(梯度下降)

原视频地址 https://www.bilibili.com/video/BV1JE411g7XF?p5 文章目录梯度下降是如何优化函数的tips1. 使用Adagrad2. Stochastic Gradient Descent3. Feature Scaling梯度下降理论基础梯度下降的局限性梯度下降是如何优化函数的 前情回顾&#xff1a;损失函数是用来衡量找到…

第九章 9.2 数组的方法(Array Methods)

注&#xff1a;这里只讲解一些 Array() 的最重要的方法。其他更多的参考手册。9.2.1 join() 将所有元素转换为字符串并默认用 "," 连接。可以指定一个附加的参数来自定义分隔符&#xff1a; vara [1, 2, 3];vars a.join(); //s "1,2,3"s a.join(", &…

HashMap vs. TreeMap vs. Hashtable vs. LinkedHashMap

http://www.importnew.com/8658.html转载于:https://www.cnblogs.com/passer1991/p/3520563.html

php7+的php-fpm参数配置,注意事项

安装php7的&#xff0c;如果php-fpm的这几个参数设置不当了&#xff0c;会导致php-fpm启动不了&#xff0c;nginx站点不能解析php文件&#xff0c;报404错误。 相关命令&#xff1a;centos7&#xff0c;启动php-fpm&#xff1a; systemctl start php-fpm查看php-fpm是否启动&am…

hung-yi lee_p10_分类/概率生成模型

文章目录研究背景本节目的本节要使用的例子研究过程把分类当成回归来算理想做法找到最佳函数的方法研究成果运用运用过程结果方法改进模型总结讨论为什么选择正态分布模型&#xff1f;关于后验概率的求法之化简与改进猜想一张图总结研究背景 本节目的 Classification:Probabi…

【跃迁之路】【495天】程序员高效学习方法论探索系列(实验阶段252-2018.06.15)...

(跃迁之路)专栏 实验说明 从2017.10.6起&#xff0c;开启这个系列&#xff0c;目标只有一个&#xff1a;探索新的学习方法&#xff0c;实现跃迁式成长实验期2年&#xff08;2017.10.06 - 2019.10.06&#xff09;我将以自己为实验对象。我将开源我的学习方法&#xff0c;方法不断…

wpf+xml实现的一个随机生成早晚餐的小demo

话说每到吃完的时间就发愁&#xff0c;真的不知道该吃什么&#xff0c;然后就想到做一个生成吃什么的小软件&#xff0c;既然这个软件如此的简单&#xff0c;就打算用wpf开发吧&#xff0c;也不用数据库了&#xff0c;直接保存在xml中就可以了 程序整体结构如下图 首先我写了一…

CentOS报错:TNS-12541: TNS:no listener TNS-12560: TNS:protocol adapter error TNS-00511: No listener

问题描述 原因 listener.ora中的ORACLE_HOME错了 解决 这个错误当时是和另一条指令lsnrctl start的错误一起报的&#xff0c;那个已解决&#xff0c;详细做法请各位移步我的另一篇博客 https://blog.csdn.net/weixin_44997802/article/details/109266708

c#数据结构———二叉查找树

using System;<?xml:namespace prefix o ns "urn:schemas-microsoft-com:office:office" />namespace BinaryTreeLibrary{///创建的是二叉查找树&#xff0c;没有重复的结点值///特点&#xff1a;左支树中任何值都小于父结点值&#xff0c;右结点任何值大于…

Spring事务管理只对出现运行期异常进行回滚

使用spring难免要用到spring的事务管理&#xff0c;要用事务管理又会很自然的选择声明式的事务管理&#xff0c;在spring的文档中说道&#xff0c;spring声明式事务管理默认对非检查型异常和运行时异常进行事务回滚&#xff0c;而对检查型异常则不进行回滚操作。那么什么是检查…

struts学习笔记三-国际化

在程序设计领域&#xff0c;人们把能够在无需改写有关代码的前提下&#xff0c;让开发出来的应用程序能够支持多种语言和数据格式的技术称为国际化技术。 国际化简称为 i18n&#xff0c;根据internationalization简化而来。 本地化简称为l10n&#xff0c;根据localization简化而…

TNS-01201: Listener cannot find executable /u01/oracle/bin/extproc for SID orcl Listener failed to

文章目录问题描述原因解决过程结果问题描述 原因 listener.ora文件中ORACLE_HOME的路径错了&#xff0c;导致按照这个路径找不到extproc 解决过程 首先去找ORACLE_HOME的路径 先切换为root用户&#xff08;这样查找时不会有文件夹进不去&#xff09; 输入指令 su root然后…

与技术无关的书单--你可以笑着说有些是“精神鸦片”

??? 转载于:https://www.cnblogs.com/crmhf/p/3823130.html