使用 dva + antd 快速开发react应用
使用 dva + antd 快速开发react应用
版本说明:
注意:dva的版本是0.9.2
$ node -v
v10.2.1 $ npm -v
5.6. $ dva -v
dva-cli version 0.9.
安装cli脚手架:
npm install dva-cli -g
使用脚手架生成应用:
dva new dva_page
建议:在new之前最好安装一下淘宝镜像,因为dva new命令会自动安装node_modules,如果使用npm会比较慢。
npm install -g cnpm --registry=https://registry.npm.taobao.org
安装antd和babel按需加载插件工具:
cd dva_page npm install antd --save npm install babel-plugin-import --D
配置babel-plugin-import:
修改根目录下的.webpackrc文件(注意前面的.,代表linux下的隐藏文件,这是roadhog的webpack配置文件)
{
"extraBabelPlugins": [
["import", {
"libraryName": "antd",
"libraryDirectory": "lib",
"style": "css"
}]
]
}
启动服务:
npm start
此时打开浏览器http://localhost:8000/#/可以看到:
编写routes:
dva默认的页面写在 \src\routes 目录下面:
我们随便引入一个antd组件,写一个demo:
import React, { Component } from 'react';
import { connect } from 'dva';
import { Timeline } from 'antd'; class Demo extends Component {
render() {
return (
<Timeline>
<Timeline.Item>Create a services site 2015-09-01</Timeline.Item>
<Timeline.Item>Solve initial network problems 2015-09-01</Timeline.Item>
<Timeline.Item>Technical testing 2015-09-01</Timeline.Item>
<Timeline.Item>Network problems being solved 2015-09-01</Timeline.Item>
</Timeline>
);
}
} Demo.propTypes = {
}; export default connect()(Demo);
修改路由router.js:
dva的路由配置默认处在 \src\routes 里,我们在里面增加一个路由:
import React from 'react';
import { Router, Route, Switch } from 'dva/router';
import IndexPage from './routes/IndexPage';
import Demo from './routes/Demo'; function RouterConfig({ history }) {
return (
<Router history={history}>
<Switch>
<Route path="/" exact component={IndexPage} />
<Route path="/demo" exact component={Demo} />
</Switch>
</Router>
);
} export default RouterConfig;
现在我们已经可以在http://localhost:8000/#/demo访问新增的页面了。
网络请求:
之前编写的都是静态页面,那么如果有网络请求和数据交互,怎么弄呢?
先完善下 \src\routes\Demo.js :
组件在willMount生命周期会dispatch数据到models层中 namespace 为demo的对象, 触发执行effects中的fetch方法。
import React, { Component } from 'react';
import { connect } from 'dva';
import { Timeline } from 'antd'; class Demo extends Component {
UNSAFE_componentWillMount() {
// dispatch -> effects -> reducer -> 更新this.props
this.props.dispatch({
type: 'demo/fetch', //models里的namespace/effects中的方法名
payload: { //models里的namespace/effects中的payload参数
time: Date.now(),
},
}).catch(err => {
// 异常可以在这里处理,比如网络请求等等
})
} render() {
// console.log(this.props);
return (
<Timeline>
<Timeline.Item>{`${new Date(this.props.new_time)}`}</Timeline.Item>
</Timeline>
);
}
} Demo.propTypes = {
}; const mapStateToProps = (state) => { //把state转换为props
console.log(state);
// 这里会把return的对象作为props传入到Demo这个类里
return state.demo;
}; export default connect(mapStateToProps)(Demo);
在 \src\services\ 中新建文件demo.js :
发送一个网络请求:
import request from '../utils/request'; export function query(params) {
return request('/api/users');
}
在 \src\models\ 中新建文件demo.js :
先引入service文件 /services/demo.js -> 定义namespace为demo -> 在effects定义generator函数 *fetch ,调用services中的请求,将请求结果放入reducers -> reducer将最终结果传入 \src\routes\Demo.js 。
import * as demo from '../services/demo'; export default { namespace: 'demo', state: {
a: 1
}, subscriptions: {
setup({ dispatch, history }) {
},
}, effects: {
// payload 是\src\routes\Demo.js dispatch 过来的参数
*fetch({ payload }, { call, put }) {
// 调用service中的请求,把请求结果存放在result中
let result = yield call(demo.query, payload.time); //如果使用 {参数} ,则是一个对象
result = { data: payload.time / 1000 }; // 因为没有配后台,所以这里result自己模拟数据
// 将result放入reducer中
yield put({
type: 'save', //reducers中的方法名
payload:{
new_time: result.data //网络返回的要保留的数据
}
});
},
}, reducers: {
save(state, action) {
// 将state和effects的put方法的payload传给\src\routes\Demo.js
return { ...state, ...action.payload };
},
}, };
在 /src/index.js 中 注册model:
import dva from 'dva';
import './index.css'; // 1. Initialize
const app = dva(); // 2. Plugins
// app.use({}); // 3. Model
// app.model(require('./models/example').default);
app.model(require('./models/demo').default); // 4. Router
app.router(require('./router').default); // 5. Start
app.start('#root');
最后在浏览器http://localhost:8000/#/demo看到:
总结:
dva的数据流可以概括为:
1. 注册model
2. 使用connect连接mode和page
3. 数据流方向: page(routes) -> (this.props.dispatch) -> model ->model/effects -> (call) -> service -> model/effects -> (put) -> reducer -> page -> (this.props)
使用 dva + antd 快速开发react应用的更多相关文章
- antd快速开发(Form篇)
antd快速开发(Form篇) 前言 由于一直在做中台业务,后台项目特别多,但是后台项目的特点是:大量的列表和大量表单,重复开发会降低效率,所以我这边总结了一下使用antd组件搭建form的快捷方法. ...
- vulcanjs 开源工具方便快速开发react graphql meteor 应用
vulcan 开源工具方便快速开发react graphql meteor 应用 操作环境mac os 安装 meteor 安装(此安装有点慢,可以通过正确上网解决) curl https://ins ...
- 使用create-react-app 快速构建 React 开发环境以及react-router 4.x路由配置
create-react-app 是来自于 Facebook,通过该命令我们无需配置就能快速构建 React 开发环境. create-react-app 自动创建的项目是基于 Webpack + E ...
- 【React】使用 create-react-app 快速构建 React 开发环境
create-react-app 是来自于 Facebook,通过该命令我们无需配置就能快速构建 React 开发环境. create-react-app 自动创建的项目是基于 Webpack + E ...
- Umi + Dva + Antd的React项目实践
记录一下最近项目所用到的技术React + Dva + Antd + umi ,以免忘记.之前没有用过它们其中一个,也是慢慢摸索,了解数据整个流程. 先了解下概念 React 不多说,3大框架之一: ...
- 快速构建 React 开发环境
使用 create-react-app 快速构建 React 开发环境 create-react-app 是来自于 Facebook,通过该命令我们无需配置就能快速构建 React 开发环境. cre ...
- 利用yeoman快速搭建React+webpack+es6脚手架
自从前后端开始分离之后,前端项目工程化也显得越来越重要了,之前写过一篇搭建基于Angular+Requirejs+Grunt的前端项目教程,有兴趣的可以点这里去看 但是有些项目可以使用这种方式,但有些 ...
- 快速了解react
概况: 通过本篇文章你可以对react的重点有个整体的认识. 关于react是什么,优点,解决什么问题等,网上一大推就不啰嗦了. 了解虚拟DOM的实现,参考这篇文章 [虚拟DOM](https://w ...
- 使用脚手架快速搭建React项目
create-react-app是Facebook官方推出的脚手架,基本可以零配置搭建基于webpack的React开发环境步骤: 打开控制台 进入你想要创建项目的目录文件下面 依次执行以下命令 np ...
随机推荐
- li标签和checkbox绑定
参考原文:https://www.cnblogs.com/youxin/p/3885496.html 我们经常需要li或span包含一个checkbox,不管点击checkbox或li都会触发相应的事 ...
- 怎样让Oracle的存储过程返回结果集
Oracle存储过程: CREATE OR REPLACE PROCEDURE getcity ( citycode IN VARCHAR2, ref_cursor OUT sys_refcursor ...
- vue hash模式和404页面的配置
1.设置我们的路由配置文件(/src/router/index.js): { path:'*', component:Error } 这里的path:’*’就是找不到页面时的配置,component是 ...
- idea搭建SSM的maven项目(tomcat容器)
一.创建maven的web项目 (1)选择项目的骨架 (2)写项目的坐标 (3)maven的设置 设置maven的本地仓库,以及配置文件的位置,同时点击+号,填入archetypeCatalog和in ...
- 监听服务器 重启apache
import requests import os import time url = 'http://www.ydyigo.com/findPwd.php' def get_server_statu ...
- 笔记——collections模块
collections模块 collections模块在内置数据类型(dict.list.set.tuple)的基础上,还提供了几个额外的数据类型:ChainMap.Counter.deque.def ...
- CodeForcesGym 100517I IQ Test
IQ Test Time Limit: 2000ms Memory Limit: 262144KB This problem will be judged on CodeForcesGym. Orig ...
- Codeforces Round #355 (Div. 2)-B. Vanya and Food Processor,纯考思路~~
B. Vanya and Food Processor time limit per test 1 second memory limit per test 256 megabytes input s ...
- j简单的分类实现-K近邻
dataSetSize=dataSet.shape[0] voteIlabel=labels[sortedDistIndicies[i]] ...
- socketserver模块使用 & websocket
socketserver: socketserver可用于实现并发通信. socketserver 模块简化了编写网络服务程序的任务:同时 SocketServer 模块也是 Python标准库中很多 ...