68dva的相关知识

#### 壹、 dva的总地址:https://github.com/dvajs/dva/blob/master/README_zh-CN.md### 贰、 dva的8个概念:https://github.com/dvajs/dva/blob/master/docs/Concepts_zh-CN.md#### 1、数据流向   数据的改变发生一般是经过用户交互行为或者浏览器行为(如路由跳转等)触发的,当此类行为会改变数据的时候能够经过 dispatch 发起一个 action,若是是同步行为会直接经过 Reducers 改变 State ,若是是异步行为(反作用)会先触发 Effects 而后流向 Reducers 最终改变 State,因此在 dva 中,数据流向很是清晰简明,而且思路基本跟开源社区保持一致(也是来自于开源社区)。![图片描述](attimg://article/content/picture/201803/04/151308p8uj0a89g8djr7u7.png)#### 2、Models一、Statetype State = anyState 表示 Model 的状态数据,一般表现为一个 javascript 对象(固然它能够是任何值);操做的时候每次都要看成不可变数据(immutable data)来对待,保证每次都是全新对象,没有引用关系,这样才能保证 State 的独立性,便于测试和追踪变化。在 dva 中你能够经过 dva 的实例属性 \_store 看到顶部的 state 数据,可是一般你不多会用到:```html:runconst app = dva();console.log(app._store); // 顶部的 state 数据```二、Actiontype AsyncAction = anyAction 是一个普通 javascript 对象,它是改变 State 的惟一途径。不管是从 UI 事件、网络回调,仍是 WebSocket 等数据源所得到的数据,最终都会经过 dispatch 函数调用一个 action,从而改变对应的数据。action 必须带有 type 属性指明具体的行为,其它字段能够自定义,若是要发起一个 action 须要使用 dispatch 函数;须要注意的是 dispatch 是在组件 connect Models之后,经过 props 传入的。```htmldispatch({  type: 'add',});```三、dispatch 函数```htmltype dispatch = (a: Action) => Action```dispatching function 是一个用于触发 action 的函数,action 是改变 State 的惟一途径,可是它只描述了一个行为,而 dipatch 能够看做是触发这个行为的方式,而 Reducer 则是描述如何改变数据的。在 dva 中,connect Model 的组件经过 props 能够访问到 dispatch,能够调用 Model 中的 Reducer 或者 Effects,常见的形式如:```htmldispatch({  type: 'user/add', // 若是在 model 外调用,须要添加 namespace  payload: {}, // 须要传递的信息});```四、Reducer```html:runtype Reducer<S, A> = (state: S, action: A) => S```Reducer(也称为 reducing function)函数接受两个参数:以前已经累积运算的结果和当前要被累积的值,返回的是一个新的累积结果。该函数把一个集合归并成一个单值。Reducer 的概念来自因而函数式编程,不少语言中都有 reduce API。如在 javascript 中:```html[{x:1},{y:2},{z:3}].reduce(function(prev, next){    return Object.assign(prev, next);})//return {x:1, y:2, z:3}```在 dva 中,reducers 聚合积累的结果是当前 model 的 state 对象。经过 actions 中传入的值,与当前 reducers 中的值进行运算得到新的值(也就是新的 state)。须要注意的是 Reducer 必须是纯函数,因此一样的输入必然获得一样的输出,它们不该该产生任何反作用。而且,每一次的计算都应该使用immutable data,这种特性简单理解就是每次操做都是返回一个全新的数据(独立,纯净),因此热重载和时间旅行这些功能才可以使用。五、EffectEffect 被称为反作用,在咱们的应用中,最多见的就是异步操做。它来自于函数编程的概念,之因此叫反作用是由于它使得咱们的函数变得不纯,一样的输入不必定得到一样的输出。dva 为了控制反作用的操做,底层引入了redux-sagas作异步流程控制,因为采用了generator的相关概念,因此将异步转成同步写法,从而将effects转为纯函数。至于为何咱们这么纠结于 纯函数,若是你想了解更多能够阅读Mostly adequate guide to FP,或者它的中文译本JS函数式编程指南。六、SubscriptionSubscriptions 是一种从 源 获取数据的方法,它来自于 elm。Subscription 语义是订阅,用于订阅一个数据源,而后根据条件 dispatch 须要的 action。数据源能够是当前的时间、服务器的 websocket 链接、keyboard 输入、geolocation 变化、history 路由变化等等。```htmlimport key from 'keymaster';...app.model({  namespace: 'count',  subscriptions: {    keyEvent(dispatch) {      key('⌘+up, ctrl+up', () => { dispatch({type:'add'}) });    },  }});```#### 3、Router这里的路由一般指的是前端路由,因为咱们的应用如今一般是单页应用,因此须要前端代码来控制路由逻辑,经过浏览器提供的 History API 能够监听浏览器url的变化,从而控制路由相关操做。dva 实例提供了 router 方法来控制路由,使用的是react-router。```htmlimport { Router, Route } from 'dva/router';app.router(({history}) =>  <Router history={history}>    <Route path="/" component={HomePage} />  </Router>);```#### 4、Route Components在组件设计方法中,咱们提到过 Container Components,在 dva 中咱们一般将其约束为 Route Components,由于在 dva 中咱们一般以页面维度来设计 Container Components。因此在 dva 中,一般须要 connect Model的组件都是 Route Components,组织在/routes/目录下,而/components/目录下则是纯组件(Presentational Components)。### 叁、 dva的6个API:https://github.com/dvajs/dva/blob/master/docs/API_zh-CN.md#### 1、app = dva(opts),建立应用,返回 dva 实例。(注:dva 支持多实例)```htmlconst app = dva({    history,    initialState,    onError,    onAction,    onStateChange,    onReducer,    onEffect,    onHmr,    extraReducers,    extraEnhancers,});```#### 2、app.use(hooks),配置 hooks 或者注册插件。(插件最终返回的是 hooks )#### 3、app.model(model),注册 model,详见 #Model 部分。#### 4、app.unmodel(namespace)取消 model 注册,清理 reducers, effects 和 subscriptions。#### 5、app.router(({ history, app }) => RouterConfig),注册路由表。```htmlapp.router(({history}) => {  return (    <Router history={history}>      <Route path="/" component={App}/>    <Router>  )})```#### 6、app.start(selector?),启动应用,selector 可选。          #### 另附1:Model。model 是 dva 中最重要的概念。如下是典型的例子:```html:runapp.model({    namespace: 'todo',    state: [],    reducers: {        add(state, { payload: todo }) {            // 保存数据到 state            return [...state, todo];        },    },    effects: {        *save({ payload: todo }, { put, call }) {            // 调用 saveTodoToServer,成功后触发 `add` action 保存到 state            yield call(saveTodoToServer, todo);            yield put({ type: 'add', payload: todo });        },    },    subscriptions: {        setup({ history, dispatch }) {            // 监听 history 变化,当进入 `/` 时触发 `load` action            return history.listen(({ pathname }) => {                if (pathname === '/') {                    dispatch({ type: 'load' });                }            });        },    },});            ```#### 另附2:model 包含 5 个属性。(1)namespace:model 的命名空间,同时也是他在全局 state 上的属性,只能用字符串,不支持经过 . 的方式建立多层命名空间。(2)state:初始值,优先级低于传给 dva() 的 opts.initialState。好比:```html:runconst app = dva({    initialState: { count: 1 },});app.model({    namespace: 'count',    state: 0,});```此时,在 app.start() 后 state.count 为 1 。(3)reducers     以 key/value 格式定义 reducer。用于处理同步操做,惟一能够修改 state 的地方。由 action 触发。     格式为 (state, action) => newState 或 [(state, action) => newState, enhancer]。(4)effects以 key/value 格式定义 effect。用于处理异步操做和业务逻辑,不直接修改 state。由 action 触发,能够触发 action,能够和服务器交互,能够获取全局 state 的数据等等。格式为 *(action, effects) => void 或 [*(action, effects) => void, { type }]。(5)subscriptions以 key/value 格式定义 subscription。subscription 是订阅,用于订阅一个数据源,而后根据须要 dispatch 相应的 action。在 app.start() 时被执行,数据源能够是当前的时间、服务器的 websocket 链接、keyboard 输入、geolocation 变化、history 路由变化等等。格式为 ({ dispatch, history }, done) => unlistenFunction。注意:若是要使用 app.unmodel(),subscription 必须返回 unlisten 方法,用于取消数据订阅。### 肆、 dva的知识地图:https://github.com/dvajs/dva-knowledgemap#### 1、JavaScript 语言一、变量声明:const 和 let,不要用 var,而是用 const 和 let,分别表示常量和变量。不一样于 var 的函数做用域,const 和 let 都是块级做用域。```htmlconst DELAY = 1000;let count = 0;count = count + 1;```二、模板字符串:模板字符串提供了另外一种作字符串组合的方法。```htmlconst user = 'world';console.log(`hello ${user}`);  // hello world// 多行const content = `  Hello ${firstName},  Thanks for ordering ${qty} tickets to ${event}.`;```三、默认参数```htmlfunction logActivity(activity = 'skiing') {  console.log(activity);}logActivity();  // skiing```四、箭头函数:函数的快捷写法,不须要经过 function 关键字建立函数,而且还能够省略 return 关键字。同时,箭头函数还会继承当前上下文的 this 关键字。好比:```html[1, 2, 3].map(x => x + 1);  // [2, 3, 4]```等同于:```html[1, 2, 3].map((function(x) {  return x + 1;}).bind(this));```五、模块的 Import 和 Export:import 用于引入模块,export 用于导出模块。好比:```html// 引入所有import dva from 'dva';// 引入部分import { connect } from 'dva';import { Link, Route } from 'dva/router';// 引入所有并做为 github 对象import * as github from './services/github';// 导出默认export default App;// 部分导出,需 import { App } from './file'; 引入export class App extend Component {};```六、ES6 对象和数组析构赋值,析构赋值让咱们从 Object 或 Array 里取部分数据存为变量。```html// 对象const user = { name: 'guanguan', age: 2 };const { name, age } = user;console.log(`${name} : ${age}`);  // guanguan : 2// 数组const arr = [1, 2];const [foo, bar] = arr;console.log(foo);  // 1```咱们也能够析构传入的函数参数。```htmlconst add = (state, { payload }) => {  return state.concat(payload);};```析构时还能够配 alias,让代码更具备语义。```htmlconst add = (state, { payload: todo }) => {  return state.concat(todo);};```对象字面量改进,这是析构的反向操做,用于从新组织一个 Object 。```htmlconst name = 'duoduo';const age = 8;const user = { name, age };  // { name: 'duoduo', age: 8 }```定义对象方法时,还能够省去 function 关键字。```htmlapp.model({  reducers: {    add() {}  // 等同于 add: function() {}  },  effects: {    *addRemote() {}  // 等同于 addRemote: function*() {}  },});```Spread Operator,Spread Operator 即 3 个点 ...,有几种不一样的使用方法。可用于组装数组。```htmlconst todos = ['Learn dva'];[...todos, 'Learn antd'];  // ['Learn dva', 'Learn antd']```也可用于获取数组的部分项。```htmlconst arr = ['a', 'b', 'c'];const [first, ...rest] = arr;rest;  // ['b', 'c']// With ignoreconst [first, , ...rest] = arr;rest;  // ['c']```还可收集函数参数为数组。```htmlfunction directions(first, ...rest) {  console.log(rest);}directions('a', 'b', 'c');  // ['b', 'c'];```代替 apply。```html:runfunction foo(x, y, z) {}const args = [1,2,3];// 下面两句效果相同foo.apply(null, args);foo(...args);```对于 Object 而言,用于组合成新的 Object 。(ES2017 stage-2 proposal)```htmlconst foo = {  a: 1,  b: 2,};const bar = {  b: 3,  c: 2,};const d = 4;const ret = { ...foo, ...bar, d };  // { a:1, b:3, c:2, d:4 }```此外,在 JSX 中 Spread Operator 还可用于扩展 props,详见 Spread Attributes。PromisesPromise 用于更优雅地处理异步请求。好比发起异步请求:```htmlfetch('/api/todos')  .then(res => res.json())  .then(data => ({ data }))  .catch(err => ({ err }));```定义 Promise 。```htmlconst delay = (timeout) => {  return new Promise(resolve => {    setTimeout(resolve, timeout);  });};delay(1000).then(_ => {  console.log('executed');});```Generatorsdva 的 effects 是经过 generator 组织的。Generator 返回的是迭代器,经过 yield 关键字实现暂停功能。这是一个典型的 dva effect,经过 yield 把异步逻辑经过同步的方式组织起来。```html:runapp.model({  namespace: 'todos',  effects: {    *addRemote({ payload: todo }, { put, call }) {      yield call(addTodo, todo);      yield put({ type: 'add', payload: todo });    },  },});```#### 2、React Component一、Stateless Functional ComponentsReact Component 有 3 种定义方式,分别是 React.createClass, class 和 Stateless Functional Component。推荐尽可能使用最后一种,保持简洁和无状态。这是函数,不是 Object,没有 this 做用域,是 pure function。好比定义 App Component 。```htmlfunction App(props) {  function handleClick() {    props.dispatch({ type: 'app/create' });  }  return <div onClick={handleClick}>${props.name}</div>}```等同于:```htmlclass App extends React.Component {  handleClick() {    this.props.dispatch({ type: 'app/create' });  }  render() {    return <div onClick={this.handleClick.bind(this)}>${this.props.name}</div>  }}```二、JSXComponent 嵌套相似 HTML,JSX 里能够给组件添加子组件。```html<App>  <Header />  <MainContent />  <Footer /></App>```classNameclass 是保留词,因此添加样式时,需用 className 代替 class 。<h1 className="fancy">Hello dva</h1>JavaScript 表达式JavaScript 表达式须要用 {} 括起来,会执行并返回结果。好比:```html<h1>{ this.props.title }</h1>```Mapping Arrays to JSX能够把数组映射为 JSX 元素列表。```html<ul>  { this.props.todos.map((todo, i) => <li key={i}>{todo}</li>) }</ul>```注释尽可能别用 // 作单行注释。```html<h1>  {}  {}  {    // single line  }  Hello</h1>```Spread Attributes这是 JSX 从 ECMAScript6 借鉴过来的颇有用的特性,用于扩充组件 props 。好比:```htmlconst attrs = {  href: 'http://example.org',  target: '_blank',};<a {...attrs}>Hello</a>```等同于```htmlconst attrs = {  href: 'http://example.org',  target: '_blank',};<a href={attrs.href} target={attrs.target}>Hello</a>```Props数据处理在 React 中是很是重要的概念之一,分别能够经过 props, state 和 context 来处理数据。而在 dva 应用里,你只需关心 props 。propTypesJavaScript 是弱类型语言,因此请尽可能声明 propTypes 对 props 进行校验,以减小没必要要的问题。```htmlfunction App(props) {  return <div>{props.name}</div>;}App.propTypes = {  name: React.PropTypes.string.isRequired,};```内置的 prop type 有:```htmlPropTypes.arrayPropTypes.boolPropTypes.funcPropTypes.numberPropTypes.objectPropTypes.string```往下传数据(示意图略)往上传数据(示意图略)三、CSS Modules定义全局 CSSCSS Modules 默认是局部做用域的,想要声明一个全局规则,可用 :global 语法。好比:```html.title {  color: red;}:global(.title) {  color: green;}```而后在引用的时候:```html<App className={styles.title} /> // red<App className="title" />        // green```classnames Package在一些复杂的场景中,一个元素可能对应多个 className,而每一个 className 又基于一些条件来决定是否出现。这时,classnames 这个库就很是有用。```htmlimport classnames from 'classnames';const App = (props) => {  const cls = classnames({    btn: true,    btnLarge: props.type === 'submit',    btnSmall: props.type === 'edit',  });  return <div className={ cls } />;}```这样,传入不一样的 type 给 App 组件,就会返回不一样的 className 组合:```html<App type="submit" /> // btn btnLarge<App type="edit" />   // btn btnSmall```#### 3、Reducerreducer 是一个函数,接受 state 和 action,返回老的或新的 state 。即:(state, action) => state增删改以 todos 为例。```htmlapp.model({  namespace: 'todos',  state: [],  reducers: {    add(state, { payload: todo }) {      return state.concat(todo);    },    remove(state, { payload: id }) {      return state.filter(todo => todo.id !== id);    },    update(state, { payload: updatedTodo }) {      return state.map(todo => {        if (todo.id === updatedTodo.id) {          return { ...todo, ...updatedTodo };        } else {          return todo;        }      });    },  },};```嵌套数据的增删改建议最多一层嵌套,以保持 state 的扁平化,深层嵌套会让 reducer 很难写和难以维护。```htmlapp.model({  namespace: 'app',  state: {    todos: [],    loading: false,  },  reducers: {    add(state, { payload: todo }) {      const todos = state.todos.concat(todo);      return { ...state, todos };    },  },});```下面是深层嵌套的例子,应尽可能避免。```htmlapp.model({  namespace: 'app',  state: {    a: {      b: {        todos: [],        loading: false,      },    },  },  reducers: {    add(state, { payload: todo }) {      const todos = state.a.b.todos.concat(todo);      const b = { ...state.a.b, todos };      const a = { ...state.a, b };      return { ...state, a };    },  },});```#### 4、Effect示例:```htmlapp.model({  namespace: 'todos',  effects: {    *addRemote({ payload: todo }, { put, call }) {      yield call(addTodo, todo);      yield put({ type: 'add', payload: todo });    },  },});```一、Effectsput用于触发 action 。```htmlyield put({ type: 'todos/add', payload: 'Learn Dva' });```call用于调用异步逻辑,支持 promise 。```htmlconst result = yield call(fetch, '/todos');```select用于从 state 里获取数据。```htmlconst todos = yield select(state => state.todos);```二、错误处理全局错误处理dva 里,effects 和 subscriptions 的抛错所有会走 onError hook,因此能够在 onError 里统一处理错误。```htmlconst app = dva({  onError(e, dispatch) {    console.log(e.message);  },});```而后 effects 里的抛错和 reject 的 promise 就都会被捕获到了。本地错误处理若是须要对某些 effects 的错误进行特殊处理,须要在 effect 内部加 try catch 。```htmlapp.model({  effects: {    *addRemote() {      try {        // Your Code Here      } catch(e) {        console.log(e.message);      }    },  },});```三、异步请求异步请求基于 whatwg-fetch,API 详见:https://github.com/github/fetchGET 和 POST```htmlimport request from '../util/request';// GETrequest('/api/todos');// POSTrequest('/api/todos', {  method: 'POST',  body: JSON.stringify({ a: 1 }),});```统一错误处理假如约定后台返回如下格式时,作统一的错误处理。```html{  status: 'error',  message: '',}```编辑 utils/request.js,加入如下中间件:```htmlfunction parseErrorMessage({ data }) {  const { status, message } = data;  if (status === 'error') {    throw new Error(message);  }  return { data };}```而后,这类错误就会走到 onError hook 里。#### 5、Subscriptionsubscriptions 是订阅,用于订阅一个数据源,而后根据须要 dispatch 相应的 action。数据源能够是当前的时间、服务器的 websocket 链接、keyboard 输入、geolocation 变化、history 路由变化等等。格式为 ({ dispatch, history }) => unsubscribe 。异步数据初始化好比:当用户进入 /users 页面时,触发 action users/fetch 加载用户数据。```htmlapp.model({  subscriptions: {    setup({ dispatch, history }) {      history.listen(({ pathname }) => {        if (pathname === '/users') {          dispatch({            type: 'users/fetch',          });        }      });    },  },});```path-to-regexp Package若是 url 规则比较复杂,好比 /users/:userId/search,那么匹配和 userId 的获取都会比较麻烦。这是推荐用 path-to-regexp 简化这部分逻辑。```htmlimport pathToRegexp from 'path-to-regexp';// in subscriptionconst match = pathToRegexp('/users/:userId/search').exec(pathname);if (match) {  const userId = match[1];  // dispatch action with userId}```#### 6、Router```htmlConfig with JSX Element (router.js)<Route path="/" component={App}>  <Route path="accounts" component={Accounts}/>  <Route path="statements" component={Statements}/></Route>```详见:react-router一、Route ComponentsRoute Components 是指 ./src/routes/ 目录下的文件,他们是 ./src/router.js 里匹配的 Component。经过 connect 绑定数据好比:```htmlimport { connect } from 'dva';function App() {}function mapStateToProps(state, ownProps) {  return {    users: state.users,  };}export default connect(mapStateToProps)(App);```而后在 App 里就有了 dispatch 和 users 两个属性。Injected Props (e.g. location)Route Component 会有额外的 props 用以获取路由信息。locationparamschildren更多详见:react-router二、基于 action 进行页面跳转```htmlimport { routerRedux } from 'dva/router';// Inside Effectsyield put(routerRedux.push('/logout'));// Outside Effectsdispatch(routerRedux.push('/logout'));// With queryrouterRedux.push({  pathname: '/logout',  query: {    page: 2,  },});```除 push(location) 外还有更多方法,详见 react-router-redux#### 7、dva 配置Redux Middleware好比要添加 redux-logger 中间件:```htmlimport createLogger from 'redux-logger';const app = dva({  onAction: createLogger(),});```注:onAction 支持数组,可同时传入多个中间件。history切换 history 为 browserHistory```htmlimport { browserHistory } from 'dva/router';const app = dva({  history: browserHistory,});```去除 hashHistory 下的 _k 查询参数```htmlimport { useRouterHistory } from 'dva/router';import { createHashHistory } from 'history';const app = dva({  history: useRouterHistory(createHashHistory)({ queryKey: false }),});```
相关文章
相关标签/搜索