记录一篇关于redux-saga的基本使用过程
作者:Chiu 发布时间:2023-07-15 16:43:19
标签:redux-saga,使用
安装
npm install --save redux
npm install --save redux-saga
配置action
actionType
创建文件src/actions/types.js,在types.js文件中添加需要的action类型
export const TEST1_ACTION = 'test1';
export const SET_TEST2_ACTION = 'change_test2';
export const SET_TEST3_ACTION = 'change_test3';
createActions
创建文件src/actions/test.js,在test.js文件中编写action
import {TEST1_ACTION, SET_TEST2_ACTION, SET_TEST3_ACTION} from './types
// 获取test1的值
export const getTest1Action = () => {
return {
type:TEST1_ACTION
}
}
// 写入test2的值
export const setTest2Action = (testValue) => {
return {
type:SET_TEST2_ACTION,
payload:testValue
}
}
// 写入test3的值
export const setTest3Action = (payload) => {
return {
type:SET_TEST3_ACTION,
payload
}
}
配置reducer
因为一个项目中可能会有很多地方需要用到reducer,所以把这些reducer文件分开管理比较好,比如:test.js,settings.js,auth.js等等。
创建文件src/reducers/test.js,编写test reducer
import {TEST1_ACTION, SET_TEST2_ACTION, SET_TEST3_ACTION} from '../actions/types
// 初始化
const initTest = {
test1:'这是test1初始化的值',
test2:'这是test2初始化的值',
test3:'这是test3初始化的值'
}
export default (state = initTest, action) =>{
switch (action.type) {
case TEST1_ACTION:{
return {
...state
}
}
case SET_TEST2_ACTION:{
return {
...state,
test2:action.payload
}
}
case SET_TEST3_ACTION:{
return {
...state,
test3:action.payload.testValue
}
}
default:
return state
}
}
创建文件src/reducers/index.js
import {combineReducers} from 'redux'
import test from './test'
const reducers = combineReducers({
test,
/*
还可以继续加入其它的reducer文件,比如:
settings,
auth,
*/
});
export default reducers;
配置saga
创建文件src/sagas/test.js
import {all,fork,put,takeEvery} from 'redux-saga/effects'
import {setTest2Action, setTest3Action} from "../actions/test"
import {SET_TEST2_ACTION, SET_TEST3_ACTION} from "../actions/actionTypes"
import axios from 'axios'
function* changeTest2 (testValue) {
yield put(setTest2Action(testValue))
}
function* changeTest3 (obj) {
try{
// 这里使用axios从网络获取数据演示,没有安装axios的需要先安装它。
// 期间响应状态码判断就省略了,就当它每次请求都成功获得testValue的数据
response = axios.get('http://localhost/api/test')
// 假设response.data里面有一个key为testValue的值
yield put(setTest3Action(response.data))
} catch (error) {
console.error('这里也可以yield put一个createAction,这里不作演示')
}
}
export function* setTest2 () {
yield takeEvery(SET_TEST2_ACTION, changeTest2)
}
export function* setTest3 () {
yield takeEvery(SET_TEST3_ACTION, changeTest3)
}
export default function* testSaga(){
yield all([
fork(setTest2),
fork(setTest3),
])
}
创建文件src/sagas/index.js
import {all} from 'redux-saga/effects';
import testSaga from './test'
export default function* rootSaga() {
yield all([
testSaga()
]);
}
配置store
import {applyMiddleware, compose, createStore} from 'redux';
import reducers from '../reducers/index';
import createSagaMiddleware from 'redux-saga';
import rootSaga from '../sagas/index';
const sagaMiddleware = createSagaMiddleware();
// 使用数组是为了方便以后继续添加中间件
const middlewares = [sagaMiddleware];
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
reducers,
composeEnhancers(applyMiddleware(...middlewares))
);
sagaMiddleware.run(rootSaga);
export default store;
App入口文件路由配置
import React from 'react'
import {Provider} from 'react-redux'
import store from './store'
import Test from './Test/'
import {BrowserRouter, Route, Switch} from "react-router-dom"
const MainApp = () =>
<Provider store={store}>
<BrowserRouter>
<Switch>
<Route path="/" component={Test}/>
</Switch>
</BrowserRouter>
</Provider>;
export default MainApp
Test.js
src/Test/index.js
import React from 'react'
import {connect} from 'react-redux'
import {setTest2Action, setTest3Action} from '../actions/test'
class Test extends React.Component {
render() {
const {test1, test2, test3, setTest2Action, setTest3Action} = this.props
return {
<div>
<div>
test1的值为:{test1}
</div>
<div>
test2的值为:{test2}
<button onClick={setTest2Action('abc')}>设置test2的值为 abc</button>
</div>
<div>
test3的值为:{test3}
<button onClick={setTest3Action()}>从网络获取test3的值</button>
</div>
</div>
}
}
}
const mapStateToProps = ({test}) => {
const {test1,test2,test3} = test;
return {test1,test2,test3}
}
export default connect (mapStateToProps,{setTest2Action, setTest3Action})(Test)
至此,即可运行 npm start
进行测试了
来源:https://segmentfault.com/a/1190000016048599


猜你喜欢
- 触发器:触发器的使用场景以及相应版本:触发器可以使用的MySQL版本:版本:MySQL5以上使用场景例子:每当增加一个顾客到某个数据库表时,
- 物化表首先提出一个不相关的IN子查询SELECT * FROM s1 WHERE key1 IN (SELECT common_field
- 目的:是学习python 多线程的工作原理,及通过抓取400张图片这种IO密集型应用来查看多线程效率对比import requestsimp
- 题目:来自Madrid且订单数少于3的消费者 建表:set nocount on --当 SET NOCOUNT 为
- cursor就是一个Cursor对象,这个cursor是一个实现了迭代器(def__iter__())和生成器(yield)的MySQLdb
- 生成一列sum_age 对age 进行累加df['sum_age'] = df['age'].cumsum(
- 这可是个综合性的问题,看看下面对文件操作的集大成代码:<% 'Set file i/
- 目录forEach()方法js中 Array.forEach如何跳出循环解决方式:总结forEach()方法语法:array.forEach
- 本文实例讲述了Python面向对象程序设计之类和对象、实例变量、类变量用法。分享给大家供大家参考,具体如下:类和对象:类的定义:用来描述具有
- 前言:今天就开始讲Python中的模块篇了,模块是Python的重要组成部分,Python之所以可以写出多种多样的程序,其实跟模块的灵活运用
- 前言文件和目录操作是很常见的功能,这里做个简单的总结,包括注意事项和实际的实现代码,基本日常开发都够用了目录操作判断目录或是文件是否存在os
- Win10系统安装MySQL8.0遇到的问题及解决方法,具体内容如下所示:对着第一个桌面应用击右键,选择“以管理员身份运行”选项,就可以以管
- 1. 基本环境安装 anaconda 环境, 由于国内登陆不了他的官网 https://www.continuum.io/downloads
- 翻译:ShiningRay @ Nirvana Studio作者:Douglas Crockford来源:http://www.crockf
- 去除字符串左右两端的空格,在vbscript里面可以轻松地使用 trim、ltrim 或 rtrim,但在js
- 利用requests、BeautifulSoup、xlwings库抓取中国银行外汇牌价首页数据1. 利用requests、Beautiful
- 1、前言接上节,我们初步体验了layui-vue的用法。相比其他ui框架,layui-vue的数据结构显得不是非常友好,但是经过数据拼凑也是
- 前言今天在学习python的过程中,发现python没有switch这个语法。于是就想在python中如何才能实现这个功能呢?正文本文中我们
- 上传控件基础知识说明:上传控件(<input type="file"/>)用于在客户端浏览并上传文件,用户选
- python的正则是通过re模块的支持匹配的3个函数match :只从字符串的开始与正则表达式匹配,匹配成功返回matchobject,否则