redux-thunk
功能: 使用中間件能夠在action中返回函數,能夠用來處理ajax異步請求
使用方法
import { createStore, applyMiddleware, compose } from 'redux';
import reducer from './reducer';
import thunk from 'redux-thunk';
// 解決 redux-devtools-extension 使用問題
const composeEnhancers =
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
const enhancer = composeEnhancers(
applyMiddleware(thunk)
);
const store = createStore(reducer, enhancer);
import { INIT_LIST_ACTION } from './actionTypes';
import axios from 'axios';
export const initListAction = (data) => ({
type: INIT_LIST_ACTION,
data
});
export const getTodoList = () => {
return (dispatch) => {
axios.get('/api/...').then(res => {
const data = res.data;
const action = initListAction(data);
dispatch(action);
})
};
};
import { INIT_LIST_ACTION } from './actionTypes';
const defaultState = {
inputValue: "",
list: []
};
export default (state = defaultState, action) => {
if(action.type === INIT_LIST_ACTION) {
const newState = JSON.parse(JSON.stringify(state));
newState.list = action.data;
return newState;
}
return state;
}
export const INIT_LIST_ACTION = 'init_list_action';
redux-saga
功能: 處理react異步請求數據,適用於大型項目
使用方法
import { createStore, applyMiddleware, compose } from 'redux';
import reducer from './reducer';
import createSagaMiddleware from 'redux-saga';
import todoSaga from './sagas';
const sagaMiddleware = createSagaMiddleware();
const composeEnhancers =
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
const enhancer = composeEnhancers(
applyMiddleware(sagaMiddleware)
);
const store = createStore(reducer, enhancer);
sagaMiddleware.run(todoSaga);
import { INIT_LIST_ACTION } from './actionTypes';
const defaultState = {
inputValue: "",
list: []
};
export default (state = defaultState, action) => {
if(action.type === INIT_LIST_ACTION) {
const newState = JSON.parse(JSON.stringify(state));
newState.list = action.data;
return newState;
}
return state;
}
// takeEvery 在每一個 GET_TODO_LIST action 被 dispatch 時調用 getTodoList
// 容許併發(譯註:即同時處理多個相同的 action)
// put 至關於store中的dispatch方法,派發action
import { takeEvery, put } from 'redux-saga/effects';
import { GET_TODO_LIST } from './actionTypes';
import { initListAction } from './actionCreators';
import axios from 'axios';
function* getTodoList() {
try {
const res = yield axios.get('/list.json');
const action = initListAction(res.data);
yield put(action);
}catch (e) {
console.log("list.json 網絡超時");
}
}
function* mySaga() {
yield takeEvery(GET_TODO_LIST, getTodoList);
}
export default mySaga;
import { GET_TODO_LIST } from './actionTypes';
export const getTodoList = () => ({
type: GET_TODO_LIST
});
export const INIT_LIST_ACTION = 'init_list_action';
export const GET_TODO_LIST = 'get_todo_list';