redux-saga中间件的使用

本文详细介绍了如何使用 Redux-Saga 中间件处理异步操作。从安装配置到具体实现,包括创建 saga 文件、在 store 中引入和运行 saga、组件中创建 action,以及在 saga 中捕获和处理 action 的全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

中间件是值action和store的中间

1、首先安装redux-saga

npm install --save redux-saga

2、在store文件夹下创建saga.js文件
3、在store下的index文件中引入

import createSagaMiddleware from 'redux-saga';
import mySaga from './sagas'
const sagaMiddleware = createSagaMiddleware()
const store = createStore(
reducer,
applyMiddleware(sagaMiddleware)
);//创建公共仓库
sagaMiddleware.run(mySaga)
export default store;

3、组件中创建action

componentDidMount(){
    const action=getInitList()
    store.dispatch(action)//这个的执行不仅reducer能接收到action,saga也能接收到
}

4、由于saga.js文件可以收到action
首先要对generrator函数熟悉
所以saga中的代码如下

import {  put, takeEvery } from 'redux-saga/effects'
import {GET_INIT_LIST} from './actiontypes'
import axios from 'axios'
import {initList} from './actionCreators'

function* getList() {
    try{
    const res=yield axios.get('/api/todolist');
    const action=initList(res.data);
    yield put(action);
}catch (e) {
    console.log("网络请求失败")
}
}
function* mySaga() {
    yield takeEvery(GET_INIT_LIST, getList);//通过这个捕获到action
}

export default mySaga;

这样就实现了redux-saga中间件的使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值