yarn add redux
yarn add react-redux
yarn add redux-thunk
yarn add redux-saga
一律在 @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
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
});
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 };
}
}
import { createStore } from 'redux';
import reducer from './reducer';
const store = createStore(reducers);
export default store;
從發出Request到收到API資料中間其實有個時間差,而且會因為網路跟資料量而延長等待時間,如果用同步的方式會讓使用者等待而使體驗感差。
異步處理的原理是當View發出一個Event給Action,Action再發出動作
redux-thunk 其實是個 middleware,利用middleware的方式,解決異步Action。
解決異步Action的library。