DVA

DVA是什么

DVA是脚手架,帮助开发者搭建框架,达到约定大于配置的效果。

框架图

99c3df68-b1b5-4eb5-a1fc-705a7769b191.png | center

优劣势

  • 优势:1.非常适用于页面局部刷新,只要更新state中的局部变量就可以做到局部页面刷新
    2.前端模块化方便,可以对一些公用的组件进行封装
    3.前后端职责明确,前端只负责对数据的渲染,后端只提供数据
    4.前端先行,可以完全不依赖后端,后端数据直接mock
    5.开发规范,约定大约配置,良好的目录层次结构,代码改写哪里写哪里
  • 劣势:1.后端开发人员需要一定的学习成本
    2.前端开发思路的转变,数据驱动页面展示

前后端分离

传统模式

402ee476-bd5e-47be-af3c-abd25ac524fc.png | center

前后端分离模式

f22d3591-50d9-4870-82e1-e2687c127053.png | center

工具

  1. npm node.js包管理工具,类似于后端的ant,maven,gradle
    常用命令:npm install dva-loading –save-dev
  2. webpack 前端打包工具

学习路径

  1. ES6、HTML

1.1 react
1.3 redux
1.3 react-redux -> 2.1 dva
1.4 redux-saga
1.5 react-router

简单示例

简单的react

React 是一个用于构建用户界面的 JAVASCRIPT 库。
React主要用于构建UI,很多人认为 React 是 MVC 中的 V(视图)。

class Counter extends React.Component {
   constructor(props) {
       super(props);
       alert("constructor");
   }

   componentWillMount() {
     alert("componentWillMount");
  }

  componentDidMount() {
     alert("componentDidMount");
  }

  componentWillReceiveProps(nextProps) {
     alert("componentWillReceiveProps");
  }

  shouldComponentUpdate() {
     alert("shouldComponentUpdate");
     return true;        // 记得要返回true
  }

  componentWillUpdate() {
    alert("componentWillUpdate");
  }

  componentDidUpdate() {
    alert("componentDidUpdate");
  }

  componentWillUnmount() {
     alert("componentWillUnmount");
  }


  render() {
    return  <div>
        <button onClick={this.props.onIncrement}>
          Increment
        </button>
        {' '}
        <button onClick={this.props.onDecrement}>
          Decrement
        </button>
        <hr />
        <div>
          Clicked: {this.props.value}  times
        </div>
      </div>;
  }
}

let state = 1
let render = () => ReactDOM.render(<Counter   
                  value={state} 
                  onIncrement ={onIncrement} />,  document.getElementById('root'));
let onIncrement = function(){
  state = state + 1
  render()
}
render()

state

state只能在内部调用setState方法修改,调用setState以后会自动render

props

props在内部是只读的,只能在外部setProps来修改props

context

在React中,数据可以以流的形式自上而下的传递,每当你使用一个组件的时候,你可以看到组件的props属性会自上而下的传递。但是,在某些情况下,我们不想通过父组件的props属性一级一级的往下传递,我们希望在某一级子组件中,直接得到上N级父组件中props中的值。
http://blog.csdn.net/tangzhl/article/details/70917258

数据流

bbc6f524-f686-4b31-8b7c-412f62b3928a.png | center

生命周期

2e54553a32b7.png | center

简单的redux

redux 主要作用是管理数据流,通过createStore方法创建一个store用来管理数据和数据维护
设计思想:
(1)Web 应用是一个状态机,视图与状态是一一对应的。
(2)所有的状态,保存在一个对象里面。

import { createStore } from 'redux'
class Counter extends React.Component {
  render() {
    return  <div>
        <button onClick={this.props.onIncrement}>
          Increment
        </button>
        {' '}
        <button onClick={this.props.onDecrement}>
          Decrement
        </button>
        <hr />
        <div>
          Clicked: {this.props.value}  times
        </div>
      </div>;
  }
}

let counterReducer = (state = 1, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1
    case 'DECREMENT':
      return state - 1
    default:
      return state
  }
}
const store = createStore(counterReducer);
const action = type => store.dispatch({type:type})

let render = () => ReactDOM.render(<Counter   
                  value={store.getState()}
                  onIncrement={() => action('INCREMENT')}
                  onDecrement={() => action('DECREMENT')}   />,  document.getElementById('root'));
render()
store.subscribe(render)

基本概念:

Store

Store 就是保存数据的地方,你可以把它看成一个容器。整个应用只能有一个 Store。

State

Store对象包含所有数据。如果想得到某个时点的数据,就要对 Store 生成快照。这种时点的数据集合,就叫做 State。当前时刻的 State,可以通过store.getState()拿到。
Redux 规定, 一个 State 对应一个 View。只要 State 相同,View 就相同。你知道 State,就知道 View 是什么样,反之亦然。

Action

State 的变化,会导致 View 的变化。但是,用户接触不到 State,只能接触到 View。所以,State 的变化必须是 View 导致的。Action 就是 View 发出的通知,表示 State 应该要发生变化了。

store.dispatch

store.dispatch()是 View 发出 Action 的唯一方法。

Reducer

Store 收到 Action 以后,必须给出一个新的 State,这样 View 才会发生变化。这种 State 的计算过程就叫做 Reducer。
Reducer 是一个函数,它接受 Action 和当前 State 作为参数,返回一个新的 State。
const reducer = function (state, action) {
// …
return new_state;
};

store.subscribe()

Store 允许使用store.subscribe方法设置监听函数,一旦 State 发生变化,就自动执行这个函数。

数据流

af757721-ddc4-41ee-8fea-2b10271d23f2.png | center

applyMiddleware

因为reducer是一个纯洁的同步方法,所以应用中间件的主要目的是为了处理异步操作
redux含有applyMiddleware这个方法,它主要对原始createStore()创建的store中dispatch方法进行重写

参考连接

https://zhuanlan.zhihu.com/p/20597452

简单的redux-saga

redux-saga是一个中间件,

import 'babel-polyfill'

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import { createStore, applyMiddleware } from 'redux'
import createSagaMiddleware,{ takeEvery }  from 'redux-saga';
import { put,call } from 'redux-saga/effects'


class Counter extends Component {
    render() {
        return  <div>
          <button onClick={this.props.onIncrement}>
            Increment
          </button>
            {' '}
          <button onClick={this.props.onDecrement}>
            Decrement
          </button>
            {' '}
            <button onClick={this.props.onIncrementAsync}>
                IncrementAsync
            </button>
            {' '}
            <button onClick={this.props.onDecrementAsync}>
                DecrementAsync
            </button>
          <hr />
          <div>
            Clicked: {this.props.value}  times
          </div>
        </div>;
    }
}


let counterReducer = (state = 1, action) => {
    switch (action.type) {
        case 'INCREMENT':
            return state + 1
        case 'DECREMENT':
            return state - 2
        default:
            return state
    }
}

export const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
//work saga
function* incrementAsync() {
    yield call(delay, 2000)
    yield put({ type: 'INCREMENT' })
}
//watcher saga: 在每个 INCREMENT_ASYNC action 调用后,派生一个新的 incrementAsync 任务
function* watchIncrementAsync() {
    yield* takeEvery('DECREMENT_ASYNC', decrementAsync)
}

const sagaMiddleware = createSagaMiddleware()
const store = applyMiddleware(sagaMiddleware)(createStore)(counterReducer)
sagaMiddleware.run(watchIncrementAsync) //sagaMiddleware.run(watchIncrementAsync) 注册了监听事件

const action = type => store.dispatch({type:type})

let render = () => ReactDOM.render(<Counter
    value={store.getState()}
    onIncrementAsync ={() =>{console.log('INCREMENT_ASYNC'); action('INCREMENT_ASYNC')}}
    onDecrementAsync ={() =>{console.log('DECREMENT_ASYNC'); action('DECREMENT_ASYNC')}}
    onIncrement={() => action('INCREMENT')}
    onDecrement={() => action('DECREMENT')}   />,     document.getElementById('root'));
render()
store.subscribe(render)

数据流

4ce2ce8d-af21-4a5d-9cff-829a776d9803.png | center

简单的react-redux

react-redux是连接react和redux的组件

import 'babel-polyfill'

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import { createStore, applyMiddleware } from 'redux'
import createSagaMiddleware,{ takeEvery }  from 'redux-saga';
import { put,call } from 'redux-saga/effects'
import { Provider, connect } from 'react-redux'


class Counter extends Component {
    render() {
        return  <div>
          <button onClick={this.props.onIncrement}>
            Increment
          </button>
            {' '}
          <button onClick={this.props.onDecrement}>
            Decrement
          </button>
            {' '}
            <button onClick={this.props.onIncrementAsync}>
                IncrementAsync
            </button>
            {' '}
            <button onClick={this.props.onDecrementAsync}>
                DecrementAsync
            </button>
          <hr />
          <div>
            Clicked: {this.props.value}  times
          </div>
        </div>;
    }
}
let ContainerCounter = connect(state => ({value:state}),
        dispatch => ({
            onIncrement : () => dispatch({type : 'INCREMENT'}),
            onDecrement : () => dispatch({type : 'DECREMENT'}),
            onIncrementAsync : () => dispatch({type : 'INCREMENT_ASYNC'})
        })
)(Counter);


let counterReducer = (state = 1, action) => {
    switch (action.type) {
        case 'INCREMENT':
            return state + 1
        case 'DECREMENT':
            return state - 2
        default:
            return state
    }
}

export const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
//work saga
function* incrementAsync() {
    yield call(delay, 2000)
    yield put({ type: 'INCREMENT' })
}
// watcher saga: 在每个 INCREMENT_ASYNC action 调用后,派生一个新的 incrementAsync 任务
function* watchIncrementAsync() {
    yield* takeEvery('INCREMENT_ASYNC', incrementAsync)
}

const sagaMiddleware = createSagaMiddleware()
const store = applyMiddleware(sagaMiddleware)(createStore)(counterReducer)
sagaMiddleware.run(watchIncrementAsync)//sagaMiddleware.run(watchIncrementAsync) 注册了监听事件

const action = type => store.dispatch({type:type})

let render = () => ReactDOM.render(
    <Provider store={store}>
        <ContainerCounter/>
    </Provider>,  document.getElementById('root'));

render()
store.subscribe(render)

Provider

Provider在根组件外面包了一层,这样一来,App的所有子组件就默认都可以拿到state了。

connect
(1)输入逻辑:外部的数据(即state对象)如何转换为 UI 组件的参数
(2)输出逻辑:用户发出的动作如何变为 Action 对象,从 UI 组件传出去。

参考连接

http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_three_react-redux.html

简单的react-router

React Router 是一个基于 React 之上的强大路由库,它可以让你向应用中快速地添加视图和数据流,同时保持页面与 URL 间的同步。

import 'babel-polyfill'

import React, { Component } from 'react'
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware } from 'redux'
import createSagaMiddleware,{ takeEvery }  from 'redux-saga';
import { put,call } from 'redux-saga/effects'
import { Provider, connect } from 'react-redux'
import {
    HashRouter as Router,
    Route,
    Link
} from 'react-router-dom';
class App  extends Component {
    render(){
        return (<div><Link to={'/counter'}>counter</Link><Link to={'/demo'}>demo</Link><br/>{this.props.children}</div>);
    }
}

class Counter extends Component {
    render() {
        return  <div>
          <button onClick={this.props.onIncrement}>
            Increment
          </button>
            {' '}
          <button onClick={this.props.onDecrement}>
            Decrement
          </button>
            {' '}
            <button onClick={this.props.onIncrementAsync}>
                IncrementAsync
            </button>
            {' '}
            <button onClick={this.props.onDecrementAsync}>
                DecrementAsync
            </button>
          <hr />
          <div>
            Clicked: {this.props.value}  times
          </div>
        </div>;
    }
}
let ContainerCounter = connect(state => ({value:state}),
        dispatch => ({
            onIncrement : () => dispatch({type : 'INCREMENT'}),
            onDecrement : () => dispatch({type : 'DECREMENT'}),
            onIncrementAsync : () => dispatch({type : 'INCREMENT_ASYNC'})
        })
)(Counter);


let counterReducer = (state = 1, action) => {
    switch (action.type) {
        case 'INCREMENT':
            return state + 1
        case 'DECREMENT':
            return state - 2
        default:
            return state
    }
}

export const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
//work saga
function* incrementAsync() {
    yield call(delay, 2000)
    yield put({ type: 'INCREMENT' })
}
// watcher saga: 在每个 INCREMENT_ASYNC action 调用后,派生一个新的 incrementAsync 任务
function* watchIncrementAsync() {
    yield* takeEvery('INCREMENT_ASYNC', incrementAsync)
}

const sagaMiddleware = createSagaMiddleware()
const store = applyMiddleware(sagaMiddleware)(createStore)(counterReducer)
sagaMiddleware.run(watchIncrementAsync)//sagaMiddleware.run(watchIncrementAsync) 注册了监听事件

let render = () => ReactDOM.render(
    <Provider store={store}>
        <Router>
            <App>
                <Route path="/counter" component={ContainerCounter} />
                <Route path="/demo" component={()=>(<div>demo</div>)} />
            </App>
        </Router>
    </Provider>,  document.getElementById('root'));
render()
store.subscribe(render)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值