dva 首先是一个基于 redux 和 redux-saga 的数据流方案,而后为了简化开发体验,dva 还额外内置了 react-router 和 fetch,因此dva是基于现有应用架构 (redux + react-router + redux-saga 等)的一层轻量封装。是由阿里架构师 sorrycc 带领 team 完成的一套前端框架。javascript
快速搭建基于react的项目(PC端,移动端)。css
第一步:安装nodehtml
第二步:安装最新版本dva-cli前端
1 $ npm install dva-cli -g 2 $ dva -v
第三步:dva new
建立新应用java
1 $ dva new myapp
也能够在建立项目目录myapp后,用dva init初始化项目
node
1 $ dva init
第四步:运行项目
react
1 $ cd myapp 2 $ npm start
浏览器会自动打开一个窗口webpack
1 import dva from 'dva'; 2 import {message} from 'antd'; 3 import './index.css'; 4 5 // 1. Initialize 建立 dva 应用实例 6 const app = dva(); 7 8 // 2. Plugins 装载插件(可选) 9 app.use({ 10 onError: function (error, action) { 11 message.error(error.message || '失败', 5); 12 } 13 }); 14 15 // 3. Model 注册model 16 app.model(require('../models/example').default); 17 18 // 4. Router 配置路由 19 app.router(require('../routes/router').default); 20 21 // 5. Start 启动应用 22 app.start('#root'); 23 24 export default app._store; // eslint-disable-line 抛出
在opts
能够配置全部的hooks
nginx
1 const app = dva({ 2 history, 3 initialState, 4 onError, 5 onHmr, 6 });
这里比较经常使用的是,history的配置,通常默认的是hashHistory
,若是要配置 history 为 browserHistory
,能够这样:git
1 import dva from 'dva'; 2 import createHistory from 'history/createBrowserHistory'; 3 const app = dva({ 4 history: createHistory(), 5 });
initialState
:指定初始数据,优先级高于 model 中的 state,默认是 {}
,可是基本上都在modal里面设置相应的state。1 app.use({ 2 onError: function (error, action) { 3 message.error(error.message || '失败', 5); 4 } 5 });
能够根据本身的须要来选择注册相应的插件
1 export default { 2 3 namespace: 'example',// 的命名空间,同时也是他在全局 上的属性,只能用字符串,咱们发送在发送 到相应的 时,就会须要用到 4 5 state: {},//表示 Model 的状态数据,一般表现为一个 javascript 对象(固然它能够是任何值) 6 7 subscriptions: {//语义是订阅,用于订阅一个数据源,而后根据条件 dispatch 须要的 action 8 setup({ dispatch, history }) { // eslint-disable-line 9 }, 10 }, 11 12 effects: {//Effect 被称为反作用,最多见的就是异步操做 13 *fetch({ payload }, { call, put }) { // eslint-disable-line 14 yield put({ type: 'save' }); 15 }, 16 }, 17 18 reducers: {//reducers 聚合积累的结果是当前 model 的 state 对象 19 save(state, action) { 20 return { ...state, ...action.payload }; 21 }, 22 }, 23 24 };modelstateactionreducernamespace
1 import React from 'react'; 2 import { routerRedux, Route ,Switch} from 'dva/router'; 3 import { LocaleProvider } from 'antd'; 4 import App from '../components/App/App'; 5 import Flex from '../components/Header/index'; 6 import Login from '../pages/Login/Login'; 7 import Home from '../pages/Home/Home'; 8 import zhCN from 'antd/lib/locale-provider/zh_CN'; 9 const {ConnectedRouter} = routerRedux; 10 11 function RouterConfig({history}) { 12 return ( 13 <ConnectedRouter history={history}> 14 <Switch> 15 <Route path="/login" component={Login} /> 16 <LocaleProvider locale={zhCN}> 17 <App> 18 <Flex> 19 <Switch> 20 <Route path="/" exact component={Home} /> 21 </Switch> 22 </Flex> 23 </App> 24 </LocaleProvider> 25 </Switch> 26 </ConnectedRouter> 27 ); 28 } 29 30 export default RouterConfig;
启动咱们本身的应用
model
是 dva
中最重要的概念,Model
非 MVC
中的 M
,而是领域模型,用于把数据相关的逻辑聚合到一块儿,几乎全部的数据,逻辑都在这边进行处理分发
1 import Model from 'dva-model'; 2 // import effect from 'dva-model/effect'; 3 import queryString from 'query-string'; 4 import pathToRegexp from 'path-to-regexp'; 5 import {ManagementPage as namespace} from '../../utils/namespace'; 6 import { 7 getPages, 8 } from '../../services/page'; 9 10 export default Model({ 11 namespace, 12 subscriptions: { 13 setup({dispatch, history}) { // eslint-disable-line 14 history.listen(location => { 15 const {pathname, search} = location; 16 const query = queryString.parse(search); 17 const match = pathToRegexp(namespace + '/:action').exec(pathname); 18 if (match) { 19 dispatch({ 20 type:'getPages', 21 payload:{ 22 s:query.s || 10, 23 p:query.p || 1, 24 j_code:parseInt(query.j,10) || 1, 25 } 26 }); 27 } 28 29 }) 30 } 31 }, 32 reducers: { 33 getPagesSuccess(state, action) { 34 const {list, total} = action.result; 35 return {...state, list, loading: false, total}; 36 }, 37 } 38 }, { 39 getPages, 40 })
model
的命名空间,同时也是他在全局 state
上的属性,只能用字符串,咱们发送在发送 action
到相应的 reducer
时,就会须要用到 namespace
初始值,咱们在 dva()
初始化的时候和在 modal
里面的 state
对其两处进行定义,其中 modal
中的优先级低于传给 dva()
的 opts.initialState
1 // dva()初始化 2 const app = dva({ 3 initialState: { count: 1 }, 4 }); 5 6 // modal()定义事件 7 app.model({ 8 namespace: 'count', 9 state: 0, 10 });
Model中state的优先级比初始化的低,可是基本上项目中的 都是在这里定义的state
Subscriptions 是一种从 源 获取数据的方法,它来自于 elm。语义是订阅,用于订阅一个数据源,而后根据条件 dispatch 须要的 action。数据源能够是当前的时间、服务器的 websocket 链接、keyboard 输入、geolocation 变化、history 路由变化等等
1 subscriptions: { //触发器。setup表示初始化即调用。 2 setup({dispatch, history}) { 3 history.listen(location => {//listen监听路由变化 调用不一样的方法 4 if (location.pathname === '/login') { 5 //清除缓存 6 } else { 7 dispatch({ 8 type: 'fetch' 9 }); 10 } 11 }); 12 }, 13 },
用于处理异步操做和业务逻辑,不直接修改 state
,简单的来讲,就是获取从服务端获取数据,而且发起一个 action
交给 reducer
的地方。其中它用到了redux-saga里面有几个经常使用的函数。
1 effects: { 2 *login(action, saga){ 3 const data = yield saga.call(effect(login, 'loginSuccess', authCache), action, saga);//call 用户调用异步逻辑 支持Promise 4 if (data && data.token) { 5 yield saga.put(routerRedux.replace('/home'));//put 用于触发action 什么是action下面会讲到 6 } 7 }, 8 *logout(action, saga){ 9 const state = yield saga.select(state => state);//select 从state里获取数据 10 }, 11 12 },
1 reducers: { 2 add1(state) { 3 const newCurrent = state.current + 1; 4 return { ...state, 5 record: newCurrent > state.record ? newCurrent : state.record, 6 current: newCurrent, 7 }; 8 }, 9 minus(state) { 10 return { ...state, current: state.current - 1}; 11 }, 12 }, 13 effects: { 14 *add(action, { call, put }) { 15 yield put({ type: 'add1' }); 16 yield call(delayDeal, 1000); 17 yield put({ type: 'minus' }); 18 }, 19 },
若是effect
与reducers
中的add
方法重合了,这里会陷入一个死循环,由于当组件发送一个dispatch
的时候,model
会首先去找effect
里面的方法,当又找到add
的时候,就又会去请求effect
里面的方法。
这里的 delayDeal,是我这边写的一个延时的函数,咱们在 utils
里面编写一个 utils.js
1 /** 2 *超时函数处理 3 * @param timeout :timeout超时的时间参数 4 * @returns {*} :返回样式值 5 */ 6 export function delayDeal(timeout) { 7 return new Promise((resolve) => { 8 setTimeout(resolve, timeout); 9 }); 10 }
接着咱们在 models/example.js
导入这个 utils.js
1 import { delayDeal} from '../utils/utils';
以key/value
格式定义 reducer
,用于处理同步操做,惟一能够修改 state
的地方。由 action
触发。其实一个纯函数。
1 reducers: { 2 loginSuccess(state, action){ 3 return {...state, auth: action.result, loading: false}; 4 }, 5 }
Router
表示路由配置信息,项目中的 router.js
RouteComponent
表示 Router
里匹配路径的 Component
,一般会绑定 model
的数据
action
的格式以下,它须要有一个 type
,表示这个 action
要触发什么操做;payload
则表示这个 action
将要传递的数据
1 { 2 type: namespace + '/login', 3 payload: { 4 userName: payload.userName, 5 password: payload.password 6 } 7 }
构建一个Action
建立函数,以下:
1 function goLogin(payload) { 2 let loginInfo = { 3 type: namespace + '/login', 4 payload: { 5 userName: payload.userName, 6 password: payload.password 7 } 8 } 9 return loginInfo 10 } 11 12 //咱们直接dispatch(goLogin()),就发送了一个action。 13 dispatch(goLogin())
type dispatch = (a: Action) => Action
dispatching function 是一个用于触发 action 的函数,action 是改变 State 的惟一途径,可是它只描述了一个行为,而 dipatch 能够看做是触发这个行为的方式,而 Reducer 则是描述如何改变数据的。
在 dva 中,connect Model 的组件经过 props 能够访问到 dispatch,能够调用 Model 中的 Reducer 或者 Effects,常见的形式如:
1 dispatch({ 2 type: namespace + '/login', // 若是在 model 外调用,须要添加 namespace,若是在model内调用 无需添加 namespace 3 payload: {}, // 须要传递的信息 4 });
先安装 antd
和 babel-plugin-import
1 npm install antd babel-plugin-import --save 2 # 或 3 yarn add antd babel-plugin-import
babel-plugin-import
也能够经过 -D
参数安装到 devDependencies
中,它用于实现按需加载。而后在 .webpackrc
中添加以下配置:
1 { 2 "extraBabelPlugins": [ 3 ["import", { 4 "libraryName": "antd", 5 "libraryDirectory": "es", 6 "style": true 7 }] 8 ] 9 }
如今就能够按需引入 antd 的组件了,如 import { Button } from 'antd'
,Button 组件的样式文件也会自动帮你引入。
1,entry是入口文件配置
单页类型:
1 entry: './src/entries/index.js',
多页类型:
1 "entry": "src/entries/*.js"
2,extraBabelPlugins 定义额外的 babel plugin 列表,格式为数组。
3,env针对特定的环境进行配置。dev 的环境变量是?development
,build 的环境变量是?production
。
1 "extraBabelPlugins": ["transform-runtime"], 2 "env": { 3 development: { 4 extraBabelPlugins: ['dva-hmr'], 5 }, 6 production: { 7 define: { 8 __CDN__: process.env.CDN ? '//cdn.dva.com/' : '/' } 9 } 10 }
开发环境下的 extraBabelPlugins 是?["transform-runtime", "dva-hmr"]
,而生产环境下是?["transform-runtime"]
4,配置 webpack 的?externals?属性
1 // 配置 @antv/data-set和 rollbar 不打入代码 2 "externals": { 3 '@antv/data-set': 'DataSet', 4 rollbar: 'rollbar', 5 }
5,配置 webpack-dev-server 的 proxy 属性。 若是要代理请求到其余服务器,能够这样配:
1 proxy: { 2 "/api": { 3 // "target": "http://127.0.0.1/", 4 // "target": "http://127.0.0.1:9090/", 5 "target": "http://localhost:8080/", 6 "changeOrigin": true, 7 "pathRewrite": { "^/api" : "" } 8 } 9 },
6,disableDynamicImport
禁用 import()
按需加载,所有打包在一个文件里,经过 babel-plugin-dynamic-import-node-sync 实现。
7,publicPath
配置 webpack 的 output.publicPath 属性。
8,extraBabelIncludes
定义额外须要作 babel 转换的文件匹配列表,格式为数组
9,outputPath
配置 webpack 的 output.path 属性。
打包输出的文件
1 config["outputPath"] = path.join(process.cwd(), './build/')
10,根据需求完整配置以下:
文件名称是:.webpackrc.js,可根据实际状况添加以下代码:
1 const path = require('path'); 2 3 const config = { 4 entry: './src/entries/index.js', 5 extraBabelPlugins: [['import', { libraryName: 'antd', libraryDirectory: 'es', style: true }]], 6 env: { 7 development: { 8 extraBabelPlugins: ['dva-hmr'], 9 }, 10 production: { 11 define: { 12 __CDN__: process.env.CDN ? '//cdn.dva.com/' : '/' } 13 } 14 }, 15 externals: { 16 '@antv/data-set': 'DataSet', 17 rollbar: 'rollbar', 18 }, 19 lessLoaderOptions: { 20 javascriptEnabled: true, 21 }, 22 proxy: { 23 "/api": { 24 // "target": "http://127.0.0.1/", 25 // "target": "http://127.0.0.1:9090/", 26 "target": "http://localhost:8080/", 27 "changeOrigin": true, 28 } 29 }, 30 es5ImcompatibleVersions:true, 31 disableDynamicImport: true, 32 publicPath: '/', 33 hash: false, 34 extraBabelIncludes:[ 35 "node_modules" 36 ] 37 }; 38 if (module.exports.env !== 'development') { 39 config["outputPath"] = path.join(process.cwd(), './build/') 40 } 41 export default config
.webpackrc
的配置请参考 roadhog 配置。先安装 antd-mobile 和 babel-plugin-import
1 npm install antd-mobile babel-plugin-import --save # 或 2 yarn add antd-mobile babel-plugin-import
babel-plugin-import
也能够经过 -D
参数安装到 devDependencies
中,它用于实现按需加载。而后在 .webpackrc
中添加以下配置:
1 { 2 "plugins": [ 3 ["import", { libraryName: "antd-mobile", style: "css" }] // `style: true` 会加载 less 文件 4 ] 5 }
如今就能够按需引入antd-mobile 的组件了,如 import { DatePicker} from '
antd-mobile'
,DatePicker 组件的样式文件也会自动帮你引入。
url
访问相关的 Route-Component
,在组件中咱们经过 dispatch
发送 action
到 model
里面的 effect
或者直接 Reducer
action
发送给Effect
,基本上是取服务器上面请求数据的,服务器返回数据以后,effect
会发送相应的 action
给 reducer
,由惟一能改变 state
的 reducer
改变 state
,而后经过connect
从新渲染组件。action
发送给reducer
,那直接由 reducer
改变 state
,而后经过 connect
从新渲染组件。以下图所示:数据的改变发生一般是经过用户交互行为或者浏览器行为(如路由跳转等)触发的,当此类行为会改变数据的时候能够经过 dispatch
发起一个 action,若是是同步行为会直接经过 Reducers
改变 State
,若是是异步行为(反作用)会先触发 Effects
而后流向 Reducers
最终改变 State
重置models里的数据:
1 dispatch({type:namespace+'/set',payload:{mdata:[]}});
set是内置的方法
1,使用match后的路由跳转问题,版本routerV4
match是一个匹配路径参数的对象,它有一个属性params,里面的内容就是路径参数,除经常使用的params属性外,它还有url、path、isExact属性。
问题描述:不能跳转新页面或匹配跳转后,刷新时url所传的值会被重置掉
不能跳转的状况
1 const {ConnectedRouter} = routerRedux; 2 3 function RouterConfig({history}) { 4 const tests =({match}) =>( 5 <div> 6 <Route exact path={`${match.url}/:tab`} component={Test}/> 7 <Route exact path={match.url} component={Test}/> 8 </div> 9 10 ); 11 return ( 12 <ConnectedRouter history={history}> 13 <Switch> 14 <Route path="/login" component={Login}/> 15 <LocaleProvider locale={zhCN}> 16 <App> 17 <Flex> 18 <Switch> 19 <Route path="/test" component={tests }/> 20 <Route exact path="/test/bindTest" component={BindTest}/> 21 22 </Switch> 23 </Flex> 24 </App> 25 </LocaleProvider> 26 </Switch> 27 </ConnectedRouter> 28 ); 29 }
路由如上写法,使用下面方式不能跳转,可是地址栏路径变了
1 import { routerRedux} from 'dva/router'; 2 ... 3 4 this.props.dispatch(routerRedux.push({ 5 pathname: '/test/bindTest', 6 search:queryString.stringify({ 7 // ...query, 8 Code: code, 9 Name: name 10 }) 11 })); 12 13 ...
能跳转,可是刷新所传的参数被重置
1 const {ConnectedRouter} = routerRedux; 2 3 function RouterConfig({history}) { 4 const tests =({match}) =>( 5 <div> 6 <Route exact path={`${match.url}/bindTest`} component={BindTest}/> 7 <Route exact path={`${match.url}/:tab`} component={Test}/> 8 <Route exact path={match.url} component={Test}/> 9 </div> 10 11 ); 12 return ( 13 <ConnectedRouter history={history}> 14 <Switch> 15 <Route path="/login" component={Login}/> 16 <LocaleProvider locale={zhCN}> 17 <App> 18 <Flex> 19 <Switch> 20 <Route path="/test" component={tests }/> 21 </Switch> 22 </Flex> 23 </App> 24 </LocaleProvider> 25 </Switch> 26 </ConnectedRouter> 27 ); 28 }
路由如上写法,使用下面方式能够跳转,可是刷新时所传的参数会被test里所传的参数重置
1 ... 2 3 this.props.dispatch(routerRedux.push({ 4 pathname: '/test/bindTest', 5 search:queryString.stringify({ 6 // ...query, 7 Code: code, 8 Name: name 9 }) 10 })); 11 12 ...
解决办法以下:地址多加一级,跳出之前的界面
路由配置
1 const {ConnectedRouter} = routerRedux; 2 3 function RouterConfig({history}) { 4 const tests =({match}) =>( 5 <div> 6 <Route exact path={`${match.url}/bind/test`} component={BindTest}/> 7 <Route exact path={`${match.url}/:tab`} component={Test}/> 8 <Route exact path={match.url} component={Test}/> 9 </div> 10 11 ); 12 return ( 13 <ConnectedRouter history={history}> 14 <Switch> 15 <Route path="/test" component={tests }/> 16 </Switch> 17 </ConnectedRouter> 18 ); 19 }
调用
1 ... 2 3 this.props.dispatch(routerRedux.push({ 4 pathname: '/test/bind/test1', 5 search:queryString.stringify({ 6 // ...query, 7 Code: code, 8 Name: name 9 }) 10 })); 11 12 ...
箭头函数的this定义:箭头函数的this是在定义函数时绑定的,不是在执行过程当中绑定的。简单的说,函数在定义时,this就继承了定义函数的对象。