React中间件 thunk&saga

  • 6-4 Redux 使用Redux-thunk中间件进行Ajax请求发送

引入thunk插件后,我们可以在actionCreators内部编写逻辑,处理请求结果。而不只是单纯的返回一个action对象。
thunk的原理,可以在actionCreators里通过返回一个函数,然后就可以在函数里编写某些异步操作了,待异步操作结束,最后通过传入的store.dispatch,发出action通知给Store要进行状态更新。

  • npm add redux-thunk
  • gitHub中搜索redux-devtools-extension 1.2目录处复制使用中间件
  • 使用异步请求的中间件
  • store/index.js 使用 thunk
import { createStore, applyMiddleware, compose} from "redux";
import reducer from "./reducer";
import thunk from "redux-thunk";

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
  ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({})
  : compose;

const enhancer = composeEnhancers(
  applyMiddleware(thunk)
);

const store = createStore(reducer, enhancer);

export default store;
  • actionCreators.js
export const getTodoList = () => {
    return () => {
      axios.get("../../todoList.json")
      .then(res => {
          const data = res.data;
        const action = getAjax(data);
        store.dispatch(action);
      })
    }
}
  • TodoList.js
const action = getTodoList ();
store.dispatch(action)
  • 6-5 什么是Redux的中间件
  • 用Redux Thunk 对Dispatch进行升级,这样就不仅可以使用对象,还能使用函数。基本没什么API,简单
    在这里插入图片描述
  • 6-6 Redux-saga 中间件的作用
  • GitHub :Redux-saga 非常大型项目更好用
  • npm add redux-saga
  • store/index.js配置
import createSagaMiddleware from 'redux-saga';
import todoSagas from './saga';
// 创建 SagaMiddleware 
const sagaMiddleware = createSagaMiddleware();
// 使用 SagaMiddleware 
const enhancer = composeEnhancers(
  applyMiddleware(thunk,sagaMiddleware)
);
// 创建sagaMiddleware 中间件
const store = createStore(reducer, enhancer);
// then run the saga 
sagaMiddleware.run(todoSagas);
  • sagas.js
import { takeEvery , put} from 'redux-saga/effects';
import { GET_INIT_LIST } from './actionType'
import { initListAction } from './actionCreators';
import axios from 'axios';

	// 一定要引入generrator 函数
function* todoSaga() {
    // 捕捉action的类型 并 执行对应方法
    yield takeEvery(GET_INIT_LIST, getInitListSaga);
}

    // 执行的方法
function* getInitListSaga() {
    try {
        const res = yield axios.get('/todoList.json');
        const action = initListAction(res.data);
        // 传给store reducer进行处理
        yield put(action);
    }catch(e) {
        console.log('list.json 404');
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值