1. 程式人生 > >react-thunk遷到redux-saga,他們的對比

react-thunk遷到redux-saga,他們的對比

thunk-saga

背景: 剛開始學習前端以及react.之前粗略的對比了下thunk以及saga.發現thunksaga總體差不多,對我來說都夠用,再考慮到學習成本,我還是選擇使用了thunk. 但是使用thunk重構幾個模組之後發現登入流程很麻煩,需要promise或者async/wait的支援才可以很好的完成登入流程,我的解決辦法是在回撥裡呼叫(嘗試過async/promis不可以,裡面的步驟比較繁瑣),這個很low逼,我也很不喜歡,以後維護起來會很吃力,所以決定切換到saga.

兩者的對比,先從簡單的獲取資料說起(獲取使用者列表)
一: 大體相同的部分

...
import * as actions from '../actions/users import {connect} from 'react-redux'; import { bindActionCreators } from 'redux' class User extends React.Component { ... } const mapStateToProps = (state, ownProps) => ({ users: state.users, }) const mapDispatchToProps = dispatch => ({ actions: bindActionCreators(actions, dispatch) }) export default connect( mapStateToProps, mapDispatchToProps )(User)

上面這部分就是大致相同的.

二: 不同點
- 配置不同
saga的store配置如下

// ./configureStore.js
import {createStore, applyMiddleware} from 'redux';
import thunkMiddleware from 'redux-thunk';
import rootReducer from './reducers';

import createSagaMiddleware from 'redux-saga';
import rootSaga from './sagas';
const sagaMiddleware = createSagaMiddleware()
// let store = createStore(combineReducers);
export default function configureStore() { const store = createStore( rootReducer, applyMiddleware(sagaMiddleware) ); sagaMiddleware.run(rootSaga) return store; }

可以發現初始化的時候就去執行 saga.

我們來看看saga:

// ./sagas/index.js
import {watchFetchUsers} from './users';

function* rootSaga() {
  /*The saga is waiting for a action called LOAD_DASHBOARD to be activated */
  yield all(
    [
      fork(watchFetchUsers),
    ]
  )
}

export default rootSaga

我們來看看watchFetchUsers

import {put, takeEvery, call} from 'redux-saga/effects';
import {queryUsers} from './Api';
import * as actions from '../../actions/users';
import {GET_USER_REQUEST} from '../../constants/users/ActionTypes'

export function * watchFetchUsers() {
  yield takeEvery(GET_USER_REQUEST, getUsers)
}

export function* getUsers() {
  const data = yield call(queryUsers);
  yield put(actions.queryUsersSuccess(data.users));
}
// ./Api
import MyFetch from '../../tools/MyFetch'

export const queryUsers = () => {
  return MyFetch.get(`v1/users`);
};

可以發現,saga裡有 watchFetchUsersgetUsers.我們在rootSagas裡是有fork這個watchFetchUsers的.然後通過watchFetchUsers去觸發getUsers. 那麼如何觸發watchFetchUsers呢?我們需要改變下使用者的actions.

// actions/users/index.js
import * as types from constants/users/ActionTypes
export const getUserRequest = () => ({type: types.GET_USER_REQUEST})

現在我們有了這個action, 那麼我們就可以去使用他發起一個請求.

// components/User.js

class User extends React.Component {
  ...
  componentDidMount() {
    this.props.actions.getUserRequest()
  }
}

這樣子他就會去執行getUserRequest方法,這樣就會被watchFetchUsers給監聽到,再去通過type(GET_USER_REQUEST)去匹配getUsers方法.
getUsers方法最後有 yield put(actions.queryUsersSuccess(data.users));這個put就是相當於thunk的dispatch.

寫了一天之後給我的感覺就是: thunk需要你自己去匹配需要的動作,saga是寫一個監聽方法,他自己去分發對應的action.
或許我這樣的寫法是不規範的,但是我還是決定先切換到saga

下面是一個關於登入傳送簡訊倒計時的對比.

  1. thunk
export const sendAuthCodeToPhone = (self, phone) => {
    return dispatch => {
      dispatch(sendCodeStart())
      MyFetch.post(`v1/verification_code`, {phone: phone}).then(data => {
        if(data.status === 200){
          dispatch(snedCodeSuccess())
          self.timer = setInterval(() => {
            dispatch(tick(self))
          }, 1000);
        }else {
          dispatch(snedCodeFail())
          message.error(data.message)
        }
      })
    }
}

const tick = (self) => {
  return dispatch => {
    let counter = self.props.login.count
    if (counter < 1) {
      clearInterval(self.timer)
      dispatch(timerStart())
    } else {
      dispatch(timerStop(counter))
    }
  }
}
  1. saga
import { eventChannel, END } from 'redux-saga'
import {put, takeEvery, call, take, fork, takeLatest} from 'redux-saga/effects';

export function* sendCode(action) {
  let {self} = action
  const result = yield call(sendCodeToPhone, action)
  if(result.status === 200){
    yield put(actions.snedCodeSuccess())
    const timeChannel = yield call(tick, self)
    try {
      while (true) {
        // take(END) will cause the saga to terminate by jumping to the finally block
        let seconds = yield take(timeChannel)
        yield put(self.props.actions.timerStop(seconds))
      }
    } finally {
      yield put(self.props.actions.timerStart())
    }
  }else {
    yield put(actions.snedCodeFail())
    message.error(result.message)
  }
}

function tick(self) {
  return eventChannel(emitter => {
      const timer = setInterval( function() {
        let counter = self.props.login.count
        if (counter < 1) {
          emitter(END)
          clearInterval(timer)
        } else {
          emitter(counter)
        }
      }, 1000);

      return () => {
        clearInterval(timer)
      }
    }
  )
}