redux-saga 小鱼儿 2022-04-04 15:13 171阅读 0赞 一、什么是redux-saga redux-saga是一个用于管理redux应用异步操作的中间件,redux-saga通过创建sagas将所有异步操作逻辑收集在一个地方集中处理,可以用来代替redux-thunk中间件。 二、编写demo 推荐使用 [https://jsbin.com/?js,output][https_jsbin.com_js_output] ![在这里插入图片描述][watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzMyNDQ3MzAx_size_16_color_FFFFFF_t_70]三、上代码 ![在这里插入图片描述][watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzMyNDQ3MzAx_size_16_color_FFFFFF_t_70 1] 整个流程:ui组件触发action创建函数 —> action创建函数返回一个action ------> action被传入redux中间件(被 saga等中间件处理) ,产生新的action,传入reducer-------> reducer把数据传给ui组件显示 -----> mapStateToProps ------> ui组件显示 import {call, put} from 'redux-saga/effects' export function* fetchData(action){ try{ const data = yield call(Api.fetchUser, action.payload.url); yield put({type: "SUCCEEDED", data}); }catch(error) yield put({type: "FAILED", error}); }; }; export function* helloSaga() { console.log('Hello Sagas!'); } // ... import { createStore, applyMiddleware } from 'redux' import createSagaMiddleware from 'redux-saga' //... import { helloSaga } from './sagas' const store = createStore( reducer, applyMiddleware(createSagaMiddleware(helloSaga)) ) // rest unchanged 《参考:[https://redux-saga-in-chinese.js.org/docs/api/index.html][https_redux-saga-in-chinese.js.org_docs_api_index.html] 》 [https_jsbin.com_js_output]: https://jsbin.com/?js,output [watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzMyNDQ3MzAx_size_16_color_FFFFFF_t_70]: /images/20220404/736ed83dade14687a126fe3af011fa64.png [watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzMyNDQ3MzAx_size_16_color_FFFFFF_t_70 1]: /images/20220404/a7c7f9fec3124f7fb10c685c9d314a0e.png [https_redux-saga-in-chinese.js.org_docs_api_index.html]: https://redux-saga-in-chinese.js.org/docs/api/index.html
还没有评论,来说两句吧...