redux-saga 使用详解说明

2024-04-29 08:18
文章标签 使用 详解 说明 redux saga

本文主要是介绍redux-saga 使用详解说明,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

redux-saga 是一个用于管理应用程序 Side Effect(副作用,例如异步获取数据,访问浏览器缓存等)的 library,它的目标是让副作用管理更容易,执行更高效,测试更简单,在处理故障时更容易。

可以想像为,一个 saga 就像是应用程序中一个单独的线程,它独自负责处理副作用。 redux-saga 是一个 redux 中间件,意味着这个线程可以通过正常的 redux action 从主应用程序启动,暂停和取消,它能访问完整的 redux state,也可以 dispatch redux action。

redux-saga 使用了 ES6 的 Generator 功能,让异步的流程更易于读取,写入和测试。通过这样的方式,这些异步的流程看起来就像是标准同步的 Javascript 代码。有点像 async/await 功能。

那他跟我们以前使用 redux-thunk 有什么区别了,不再会遇到回调地狱了,你可以很容易地测试异步流程并保持你的 action 是干净的。

接下来我们详细的说明如何接入我们自己的项目。react 项目搭建我们这就不累赘,直接用 create-react-app 脚手架创建一个。这个网上很多教程,用起来也很简单,构建能力也很强,适合基本所有项目。后面代码标记加粗的部分是我们需要在脚手架基本上编辑的代码。

redux-saga 故名思议它是跟 redux 一起用的,是解决 react 状态管理副作用的一个中间件。下面我们以一些案例来学习这个中间件,开启我们的神奇之旅。

  • 安装 react-redux redux-saga
npm i -S react-redux redux-saga
  • src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import { composeWithDevTools } from 'redux-devtools-extension'; // 与谷歌插件配合可以更直观的在浏览器上查看redux state 状态
import createSagaMiddleware from 'redux-saga';
import rootReducer from './reducers';
import mySaga from './sagas';const sagaMiddleware = createSagaMiddleware();
const store = createStore(rootReducer,composeWithDevTools(applyMiddleware(sagaMiddleware))
)
sagaMiddleware.run(mySaga)ReactDOM.render(<Provider store={store}><App /></Provider>,document.getElementById('root')
);// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
  • 新建 sagas 目录 index.js
import { all } from 'redux-saga/effects';
import { add } from './counter';export default function* rootSaga() {yield all([add()])
}
  • sagas/counter.js
import { put, takeEvery, delay } from 'redux-saga/effects';function* increase() {yield delay(1000); // 等待1秒yield put({ type: 'INCREMENT' }); // 命令 middleware 向 Store 发起一个 action
}// 监听异步自增事件
export function* add() {yield takeEvery('INCREMENT_ASYNC', increase);
}
  • 新增reducers目录 index.js
import { combineReducers } from 'redux';
import counter from './counter';export default combineReducers({counter
})
  • reducers/counter.js
const counter = (state = 1, action = {}) => {switch(action.type) {case 'INCREMENT':return state + 1;default:return state;}
}export default counter;
  • 新建actions目录 index.js
// 自增
export const increate = () => {return {type: 'INCREMENT'}
}// 异步自增(等待1秒才触发自增action)
export const increateAsync = () => {return {type: 'INCREMENT_ASYNC'}
}
  • 自增组件
import React from 'react';
import { connect } from 'react-redux';
import { increate, increateAsync } from '../actions';class CustomCounter extends React.Component {render() {return (<div className="custom-counter" style={{padding: 50}}><div style={{ marginBottom: '20px' }}><p>{this.props.counter}</p><button onClick={()=>this.props.increate()}>自增</button><button onClick={()=>this.props.increateAsync()}>异步自增</button></div></div>)}
}const mapStateToProps = (state) => {return {counter: state.counter}
}export default connect(mapStateToProps, { increate, increateAsync })(CustomCounter);

这是一个相对简单的自增组件,利用到了 redux-saga。但是从代码不能看出他的 Generator 功能确实使代码看起来可读性要好一些。而且抽离一层出来,使得 redux 代码更加的清晰。下面我们来一个稍复杂一点的案例,异步请求接口获取用户信息。这里请求接口用到了 react 代理功能,react proxy 配置请参考:https://www.ifrontend.net/2021/07/react-proxy/

这里我们用到另个非常好用的 ajax 模块, axios,下面安装一下吧

npm i -S axios
  • 新建一个 fetchUser.js 获取用户信息的 saga
import { call, takeEvery, put } from 'redux-saga/effects';
import axios from 'axios';function* fetch_user() {try {const userInfo = yield call(axios.get, '/api/getUserInfo');yield put({ type: 'FETCH_SUCCESS', userInfo: userInfo.data });} catch (e) {yield put({ type: 'FETCH_FAIL', error: e });}
}function* user() {yield takeEvery('FETCH_REQUEST', fetch_user);
}const rootUser = [user()
]export default rootUser;
  • 新建一个 users.js reducer
const initialState = {isFetch: false,error: null,userInfo: null
}const user = (state = initialState, action = {}) => {switch (action.type) {case 'FETCH_REQUEST':return {...state,isFetch: true}case 'FETCH_SUCCESS':return {...state,isFetch: false,userInfo: action.userInfo}case 'FETCH_FAIL':return {...state,isFetch: false,error: action.error}  default:return state;}
}export default user;
  • 新建一个 users.js action
export const fetchUser = () => {return {type: 'FETCH_REQUEST'}
}
  • CustomUserInfo 组件
import React from 'react';
import { connect } from 'react-redux';
import { fetchUser } from '../actions/users.js';class CustomUser extends React.Component {render() {const { isFetch, error, userInfo } = this.props.user;let data = ''if (isFetch) {data = '正在加载中...'} else if (userInfo) {data = userInfo.name;} else if (error) {data = error.message;}return (<div className="custom-user" style={{padding: 50}}><div style={{ marginBottom: '20px' }}><button onClick={()=>this.props.fetchUser()}>axios请求</button ></div><h2>{data}</h2></div>)}
}const mapStateToProps = (state) => {return {user: state.user}
}export default connect(mapStateToProps, { fetchUser })(CustomUser);
  • 这里用到了一个 api/getUserInfo 的接口,笔者是采用 node.js koa 做的,这里也贴一下代码。
const koa = require('koa');
const app = new koa();
const Router = require('koa-router');
const router = new Router();router.get('/api/getUserInfo', async (ctx, next) => {ctx.body={state:"success",name: '伍哥的传说'};
})// 启动路由
app.use(router.routes()).use(router.allowedMethods())app.listen(3001, () => {console.log('server is running at http://localhost:3001')
});

经过这个是不是越来越觉得 redux-saga 好用了,答案是肯定的,用 redux-thunk 时有异步操作时,除了有可能会回调地狱,ajax 请求的业务逻辑也是跟 action 柔在一起的。代码没有这么清晰。

当然 redux-saga 就这些作用,功能吗。肯定不止这些,下面我们一一来尝试!

  • 监听未来的 action

日志记录器:Saga 将监听所有发起到 store 的 action,并将它们记录到控制台。
使用 takeEvery(‘*’)(使用通配符 * 模式),我们就能捕获发起的所有类型的 action。

import { select, takeEvery } from 'redux-saga/effects'function* watchAndLog() {yield takeEvery('*', function* logger(action) {const state = yield select()console.log('action', action)console.log('state after', state)})
}

待更新…

前端开发那点事

微信公众号搜索“前端开发那点事”

这篇关于redux-saga 使用详解说明的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/945566

相关文章

python使用库爬取m3u8文件的示例

《python使用库爬取m3u8文件的示例》本文主要介绍了python使用库爬取m3u8文件的示例,可以使用requests、m3u8、ffmpeg等库,实现获取、解析、下载视频片段并合并等步骤,具有... 目录一、准备工作二、获取m3u8文件内容三、解析m3u8文件四、下载视频片段五、合并视频片段六、错误

CSS place-items: center解析与用法详解

《CSSplace-items:center解析与用法详解》place-items:center;是一个强大的CSS简写属性,用于同时控制网格(Grid)和弹性盒(Flexbox)... place-items: center; 是一个强大的 css 简写属性,用于同时控制 网格(Grid) 和 弹性盒(F

gitlab安装及邮箱配置和常用使用方式

《gitlab安装及邮箱配置和常用使用方式》:本文主要介绍gitlab安装及邮箱配置和常用使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1.安装GitLab2.配置GitLab邮件服务3.GitLab的账号注册邮箱验证及其分组4.gitlab分支和标签的

spring中的ImportSelector接口示例详解

《spring中的ImportSelector接口示例详解》Spring的ImportSelector接口用于动态选择配置类,实现条件化和模块化配置,关键方法selectImports根据注解信息返回... 目录一、核心作用二、关键方法三、扩展功能四、使用示例五、工作原理六、应用场景七、自定义实现Impor

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

nginx启动命令和默认配置文件的使用

《nginx启动命令和默认配置文件的使用》:本文主要介绍nginx启动命令和默认配置文件的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录常见命令nginx.conf配置文件location匹配规则图片服务器总结常见命令# 默认配置文件启动./nginx

在Windows上使用qemu安装ubuntu24.04服务器的详细指南

《在Windows上使用qemu安装ubuntu24.04服务器的详细指南》本文介绍了在Windows上使用QEMU安装Ubuntu24.04的全流程:安装QEMU、准备ISO镜像、创建虚拟磁盘、配置... 目录1. 安装QEMU环境2. 准备Ubuntu 24.04镜像3. 启动QEMU安装Ubuntu4

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

Windows下C++使用SQLitede的操作过程

《Windows下C++使用SQLitede的操作过程》本文介绍了Windows下C++使用SQLite的安装配置、CppSQLite库封装优势、核心功能(如数据库连接、事务管理)、跨平台支持及性能优... 目录Windows下C++使用SQLite1、安装2、代码示例CppSQLite:C++轻松操作SQ

一文深入详解Python的secrets模块

《一文深入详解Python的secrets模块》在构建涉及用户身份认证、权限管理、加密通信等系统时,开发者最不能忽视的一个问题就是“安全性”,Python在3.6版本中引入了专门面向安全用途的secr... 目录引言一、背景与动机:为什么需要 secrets 模块?二、secrets 模块的核心功能1. 基