--- title: Redux & Thunk & Saga 學習筆記 tags: Front-end, React, Redux, 筆記 --- # 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: ```javascript= 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](https://redux.js.org/) ### Three Parts [PS寫的Redux筆記](https://hackmd.io/bTHCKUJFTiOdvH9tRWwHSw) - Action: ```javascript= 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: ```javascript= 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: ```javascript= import { createStore } from 'redux'; import reducer from './reducer'; const store = createStore(reducers); export default store; ``` ## Async Action 從發出Request到收到API資料中間其實有個時間差,而且會因為網路跟資料量而延長等待時間,如果用同步的方式會讓使用者等待而使體驗感差。 ![](https://i.imgur.com/6TWDmKI.gif) > 圖源:[Redux Sagas - Chirpy_me - Medium](https://medium.com/@aksudupa11/redux-sagas-714370b61692) > 異步處理的原理是當View發出一個Event給Action,Action再發出動作 ## [Redux-thunk](https://github.com/reduxjs/redux-thunk) redux-thunk 其實是個 middleware,利用middleware的方式,解決異步Action。 ```javascript= ``` ```javascript= ``` ```javascript= ``` ## [Redux-saga](https://github.com/redux-saga/redux-saga) 解決異步Action的library。 ## 爆炸的資料來源: - [我]() - [Read Me | Redux](https://chentsulin.github.io/redux/index.html) - [Read Me | redux-saga](https://jiepeng.me/redux-saga/)