1. 程式人生 > >redux-saga案例使用

redux-saga案例使用

redux-saga的配置

store/index.js
import { createStore,applyMiddleware,compose } from 'redux'
import createSagaMiddleware from 'redux-saga'
import reducer from './reducer'
import todoSagas from './sagas'
const sagaMiddleware = createSagaMiddleware();

const composeEnhancers =
    typeof window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
        window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
const enhancer = composeEnhancers(
    applyMiddleware(sagaMiddleware),
    // applyMiddleware(thunk),
);
const store = createStore(reducer,enhancer);
sagaMiddleware.run(todoSagas);
export default store;

store/sagas.js

import { takeEvery,put} from 'redux-saga/effects'
import axios from'axios'
import { GET_INIT_LIST } from './actionTypes'
import { initListAction } from './actionCreators'
必須是genenrator函式
function* getInitList(){
    // 利用try...catch...語句來捕獲ajax異常
    try{
        //吧非同步的程式碼寫在try裡面,如果ajax的介面都能
        // 正確的執行並且獲取到資料了,就只走try裡面的程式碼,
        //一旦獲取介面有錯的話就會走到catch裡面
const res=yield axios.get('/list.json'); const data = res.data; const action=initListAction(data); yield put(action); }catch(e){ console.log("網路請求失敗"); } } function* mySaga() { yield takeEvery(GET_INIT_LIST, getInitList); } export default mySaga;

src/TodoList2.js

componentDidMount(){
    const action=getInitList();
    store.dispatch(action);
}

store/reducer.js

// 筆記本
/*
state[整個圖書館裡所有書籍的資訊]/store之前的所有資料
 */
import {CHANGE_INPUT_VALUE,ADD_TODO_ITEM,DELETE_ITEMD,INIT_LIST_ACTION} from './actionTypes'
const defaultState = {
    inputValue:'123',
    list:[1,2]
};
//reducer可以接受state,但是絕不能修改state
//reducer必須是純函式-純函式指的是,給定固定的輸入,
// 就一定會有固定的輸出,而且不會有任何的副作用
//一旦函式裡面有setTimeout
// 或者是ajax請求
// 或者是和日期相關的 new Date()
//就不再是純函數了,reducer裡面不能有非同步和對時間的操作
export default (state=defaultState,action)=>{
    if(action.type===CHANGE_INPUT_VALUE){
        const newState = JSON.parse(JSON.stringify(state));
修改inputValue值
        newState.inputValue=action.value;
        // state.inputValue=action.value 不能對state修改,這樣就會產生副作用
        return newState;
    }
    if(action.type===ADD_TODO_ITEM){
        const newState=JSON.parse(JSON.stringify(state));
向list新增值
        newState.list.push(newState.inputValue);
        newState.inputValue='';
        console.log("newState:",newState);
        return newState;
    }
    if(action.type===DELETE_ITEMD){
        const newState=JSON.parse(JSON.stringify(state));
        let index=action.value;
刪除list中的值
        newState.list.splice(index,1);
        return newState;
    }
    if(action.type===INIT_LIST_ACTION){
        const newState=JSON.parse(JSON.stringify(state));
初始化list中的資料
        newState.list=action.data;
        return newState;
    }
    // console.log(state,action);
    return state;
}