Try   HackMD

Redux & Thunk & Saga 學習筆記

Install

  • redux
    • yarn add redux
  • react-redux
    • yarn add react-redux
  • redux-thunk
    • yarn add redux-thunk
  • redux-saga
    • yarn add redux-saga

ActionType

一律在 @constants/actionTypes.js 中定義。

Usually there will be 3 types for an action, like this:

export const AUTH_LOGIN = 'AUTH_LOGIN'; export const AUTH_LOGIN_SUCCESS = 'AUTH_LOGIN_SUCCESS'; export const AUTH_LOGIN_ERROR = 'AUTH_LOGIN_ERROR';

The action is login, you

Redux

Three Parts

PS寫的Redux筆記

  • Action:
export const authLogin = (id) => ({ type: AUTH_LOGIN, payload: id }); export const authLoginSuccess = (payload) => ({ type: AUTH_LOGIN_SUCCESS, payload: payload }); export const authLoginError = (error) => ({ type: AUTH_LOGIN_ERROR, payload: error });
  • Reducer:
const INIT_STATE = { loading: false }; export default (state = INIT_STATE, action) => { switch (action.type) { case AUTH_LOGIN: return { ...state, loading: false }; case AUTH_LOGIN_SUCCESS: return { ...state, loading: true}; case AUTH_LOGIN_ERROR: return { ...state, loading: true, error: action.payload }; default: return { ...state }; } }
  • Store:
import { createStore } from 'redux'; import reducer from './reducer'; const store = createStore(reducers); export default store;

Async Action

從發出Request到收到API資料中間其實有個時間差,而且會因為網路跟資料量而延長等待時間,如果用同步的方式會讓使用者等待而使體驗感差。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

圖源:Redux Sagas - Chirpy_me - Medium

異步處理的原理是當View發出一個Event給Action,Action再發出動作

Redux-thunk

redux-thunk 其實是個 middleware,利用middleware的方式,解決異步Action。

Redux-saga

解決異步Action的library。

爆炸的資料來源: