redux-saga案例使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/pansuyong/article/details/82918265

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;
}


 

猜你喜欢

转载自blog.csdn.net/pansuyong/article/details/82918265