记录一篇关于redux-saga的基本使用过程

作者:Chiu 时间:2023-07-15 16:43:19 

安装


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

标签:redux-saga,使用
0
投稿

猜你喜欢

  • 微信小程序动态添加分享数据

    2024-06-20 16:23:00
  • Python import自己的模块报错问题及解决

    2023-11-09 15:57:08
  • python数据类型之间怎么转换技巧分享

    2023-09-04 02:38:42
  • Python实现方便使用的级联进度信息实例

    2021-04-22 12:31:18
  • pygame学习笔记(2):画点的三种方法和动画实例

    2021-09-02 19:59:51
  • 为FCKeditor2.6添加行距功能(最新修改)

    2008-08-18 21:09:00
  • python字符串拼接+和join的区别详解

    2021-10-19 01:26:39
  • Python实现合并同一个文件夹下所有PDF文件的方法示例

    2021-01-21 23:08:18
  • 简单form标准化实例——语义结构

    2007-06-20 16:32:00
  • vue和react等项目中更简单的实现展开收起更多等效果示例

    2024-05-29 22:47:35
  • Python map和reduce函数用法示例

    2022-06-21 09:02:25
  • django rest framework vue 实现用户登录详解

    2022-04-15 00:53:52
  • Python实现读取SQLServer数据并插入到MongoDB数据库的方法示例

    2022-11-16 04:14:21
  • Echarts图表移动端横屏进入退出的实现

    2024-05-11 09:06:45
  • 一个挺酷的星级投票效果

    2010-08-03 12:44:00
  • Django程序的优化技巧

    2023-11-10 00:29:24
  • Pytorch之卷积层的使用详解

    2022-09-04 16:43:21
  • 详细讲解删除SQL Server日志的具体方法

    2008-12-09 14:32:00
  • 利用Python小工具实现3秒钟将视频转换为音频

    2023-05-26 21:11:34
  • Javascript:keyCode键盘键码值表

    2008-02-21 13:16:00
  • asp之家 网络编程 m.aspxhome.com