redux-thunk

action creator

  1. export const fetchTasksStarted = () => ({
  2. type: "FETCH_TASKS_START"
  3. });
  4. export const fetchTasksSuccess = tasks => ({
  5. type: "FETCH_TASKS_SUCCESS",
  6. payload: tasks
  7. });
  8. export const fetchTasksError = errorMessage => ({
  9. type: "FETCH_TASKS_ERROR",
  10. payload: errorMessage
  11. });
  12. const fetchTasks = () => async dispatch => {
  13. dispatch(fetchTasksStarted())
  14. try{
  15. const TaskResponse = await fetch("API URL")
  16. const task = await taskResponse.json()
  17. dispatch(fetchTasksSuccess(tasks))
  18. }catch(exc){
  19. dispatch(fetchTasksError(error.message))
  20. }
  21. }

fetchTasksReducer

  1. ...
  2. const INITIAL_STATE = {
  3. tasks: null,
  4. isFetching: false,
  5. errorMessage: undefined
  6. };
  7. const fetchTasksReducer = (state = INITIAL_STATE, action) => {
  8. switch (action.type) {
  9. case "FETCH_TASKS_START":
  10. return {
  11. ...state,
  12. isFetching: true
  13. };
  14. case "FETCH_TASKS_SUCCESS":
  15. return {
  16. ...state,
  17. isFetching: false,
  18. tasks: action.payload
  19. };
  20. case "FETCH_TASKS_ERROR":
  21. return {
  22. ...state,
  23. isFetching: false,
  24. errorMessage: action.payload
  25. };
  26. default:
  27. return state;
  28. }
  29. };
  30. export default fetchTasksReducer;

redux-saga

image.png

Saga 辅助函数

  • takeEvery
  • takeLatest
    • takeLatest(pattern, saga, …args)
      • pattern: String | Array | Function
      • 当 action 被发起到 Store,并且匹配 pattern 时,则 takeLatest 会在后台启动一个新的 saga 任务,如果之前有一个 saga 任务启动了,并且仍在执行中,那么这个任务将被取消。
      • takeLatest 是由 take 和 fork 构建的高级 API
    • takeLatest(channel, saga, …args)
  • throttle

    Effect 创建函数

  • take(pattern)

    • take(channel)
  • call(fn, …args)
    • 创建一个 Effet
    • fn 可以是一个普通函数,也可以是一个 Generator 函数,middleware 会调用该函数
    • call([context, fnName], …args)
      • yield call([localStorage, ‘getItem’], ‘redux-saga’)
  • put(action)
  • fork
  • spawn
  • cancel
  • select

    Effect 组合

参考

记一次redux-saga的项目实践总结

redux-saga 官方文档