- 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 為一個(gè)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 loadJokeListAction = createAction(GET_MOBILE, () => loadJokeList())
流程是:action => api => reducer
- Redux-Saga
Redux-Saga 是監(jiān)聽action蛋济,一旦對(duì)應(yīng)的action觸發(fā)就執(zhí)行對(duì)應(yīng)的saga回調(diào)
// 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 的缺點(diǎn)在于api層與store耦合洛勉,優(yōu)點(diǎn)是比較靈活页屠,易于控制
2、redux-promise的優(yōu)點(diǎn)是api層與store解耦特幔,缺點(diǎn)是對(duì)請(qǐng)求失敗咨演,請(qǐng)求中的情形沒有很好的處理
3、redux-saga 的優(yōu)點(diǎn)是api層與store解耦蚯斯,對(duì)請(qǐng)求中薄风,請(qǐng)求失敗都有完善的處理饵较,缺點(diǎn)是代碼量較大。