美文网首页
Redux-Thunk & Redux-Promise

Redux-Thunk & Redux-Promise

作者: 风之化身呀 | 来源:发表于2018-08-12 23:17 被阅读647次
    • Redux-Thunk
      其store下的actions只是普通的actionCreator,真正异步操作放在API里
    // api.js
    import { loadJoke } from 'store/actions'
    const loadJokeList = ({
      sort = 'asc',
      page = 1,
      pagesize = 10,
      time = '1418816972'
    } = {}) => dispatch =>
      get('joke/content/list.php', {
        sort,
        page,
        pagesize,
        time,
        key: '9c818748074635227d7b2060c2450c5d'
      }).then(data => dispatch(loadJoke(data)))
    
    // store/actions
    import { LOAD_JOKE } from '../actionType'
    import { createAction } from 'redux-actions'
    // 语法:createAction(type, payloadCreator)
    export const loadJoke = createAction(LOAD_JOKE, data => data.result.data)
    

    流程是:api => action => reducer

    • Redux-Promise
      其store下的actions不是普通的actionCreator,action.payload 为一个Promise
    // api.js
    const loadJokeList = ({
      sort = 'asc',
      page = 1,
      pagesize = 10,
      time = '1418816972'
    } = {}) =>
      get('joke/content/list.php', {
        sort,
        page,
        pagesize,
        time,
        key: '9c818748074635227d7b2060c2450c5d'
      })
    // store/actions
    import { GET_MOBILE } from '../actionType'
    import { getMobile } from 'api'
    import { createAction } from 'redux-actions'
    // 语法:createAction(type, payloadCreator)
    export const getMobileAction = createAction(GET_MOBILE, () => getMobile())
    

    流程是:action => api => reducer

    • Redux-Saga
      Redux-Saga 是监听action,一旦对应的action触发就执行对应的saga回调
    // sagas/index.js
    import { call, put } from 'redux-saga/effects'
    import { takeEvery } from 'redux-saga'
    import { getMobile } from 'api'
    import { FETCH_FAIL, FETCH_SUCCEED, FETCH_REQUESTED } from 'store/actionType'
    
    function* fetchData(action) {
      try {
        const payload = yield call(getMobile)
        yield put({ type: FETCH_SUCCEED, payload })
      } catch (error) {
        yield put({ type: FETCH_FAIL, error })
      }
    }
    
    export default function* watchFetchData() {
      yield* takeEvery(FETCH_REQUESTED, fetchData)
    }
    
    // App.js
      componentWillMount() {
        this.props.dispatch({ type: 'FETCH_REQUESTED' })
      }
    

    流程是:saga => api => reducer

    比较

    1、redux-thunk 的缺点在于api层与store耦合,优点是比较灵活,易于控制
    2、redux-promise的优点是api层与store解耦,缺点是对请求失败,请求中的情形没有很好的处理
    3、redux-saga 的优点是api层与store解耦,对请求中,请求失败都有完善的处理,缺点是代码量较大。

    相关文章

      网友评论

          本文标题:Redux-Thunk & Redux-Promise

          本文链接:https://www.haomeiwen.com/subject/mwvebftx.html