当前位置:网站首页>redux-thunk 简单案例,优缺点和思考
redux-thunk 简单案例,优缺点和思考
2022-06-26 03:06:00 【一个抱抱一首歌】
redux-thunk
实现一个异步的加数器
框架为: react + react-redux + redux-thunk
项目结构

代码如下
新建一个 component -> App.js , 代码如下
// App.js
import '@babel/polyfill'
import * as React from 'react'
import {
render } from 'react-dom'
import {
Provider } from 'react-redux'
import Index from './Index'
import {
createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import rootReducer from '../reducers'
const enhancer = applyMiddleware(thunk);
const configureStore = createStore(
rootReducer,
enhancer
);
function Main() {
return <Provider store={
configureStore}>
<Index />
</Provider>
}
export default Main
Services
新建 services -> index.js , 接口层
export function getData(){
return Promise.resolve({
num:1})
}
Actions
新建 actions -> index.js
export const ADD_COUNT = 'ADD_COUNT'
export const ADD_COUNT_ASYNC = 'ADD_COUNT_ASYNC'
export const DECREASE_COUNT = 'DECREASE_COUNT'
import {
getData} from '../services/index'
export function add_count(num) {
return {
type: ADD_COUNT,
num,
}
}
export const add_count_sync = () => (dispatch) => {
setTimeout(() => {
getData().then(res => {
console.log(res)
const {
num } = res;
dispatch(add_count(num));
})
}, 1000);
}
Reducers
新建 reducers -> index.js
// index.js
import {
combineReducers } from 'redux';
function count_change(state = 0, action = {
}) {
console.log(action)
switch (action.type) {
case 'ADD_COUNT':
state = state + action.num
break;
default:
break;
}
return state
}
export default combineReducers({
count_change
})
Components
新建一个 components -> Index.js
import React from 'react'
import {
connect} from 'react-redux'
import {
add_count , add_count_sync} from '../actions/index'
import {
getData} from '../services/index'
function Index(props) {
return <div>
当前数据 {
props.state} <br></br>
<button onClick={
()=>{
props.add_count_sync()
}}>点击我</button>
</div>
}
const mapStateToProps = function(store) {
return {
state: store.count_change
}
}
export default connect(mapStateToProps,{
add_count_sync})(Index)
Redux-thunk 优缺点总结
优点
- 代码简洁明了
- 库代码量小
缺点
- 由于先调用的是接口层,导致代码可能会特别臃肿 , 设想一个例子
如果一个接口既需要触发 action 的 `A1` ,而且还需要触发 `A2`,
这样子可能会使得接口在异步的时候需要判断需要触发哪个 action , 会使得代码难以维护
补充
最新看了下大佬一些 blog, 顺便看了下 react-thunk 源码 , 只有非常简单的几句话,就是一个 柯理化函数
// node_modules\redux-thunk\es\index.js
/** A function that accepts a potential "extra argument" value to be injected later, * and returns an instance of the thunk middleware that uses that value */
function createThunkMiddleware(extraArgument) {
// Standard Redux middleware definition pattern:
// See: https://redux.js.org/tutorials/fundamentals/part-4-store#writing-custom-middleware
var middleware = function middleware(_ref) {
var dispatch = _ref.dispatch,
getState = _ref.getState;
return function (next) {
return function (action) {
// The thunk middleware looks for any functions that were passed to `store.dispatch`.
// If this "action" is really a function, call it and return the result.
// action 其实就是我们的 动态 antion
if (typeof action === 'function') {
// Inject the store's `dispatch` and `getState` methods, as well as any "extra arg"
return action(dispatch, getState, extraArgument);
} // Otherwise, pass the action down the middleware chain as usual
return next(action);
};
};
};
return middleware;
}
var thunk = createThunkMiddleware(); // Attach the factory function so users can create a customized version
// with whatever "extra arg" they want to inject into their thunks
思考
这里有个 问题 , 其实上诉的 方法 不用 react-thunk , 也能实现 , 完全不用去实现 asyncAction ,而且 action 也是 pure
const mapDispatchToProps = (dispatch) => {
return {
getMenuTreeFn: () => {
setTimeout(() => {
getData().then(res => {
console.log(res)
const {
num } = res;
dispatch(add_count(num));
})
}, 5000);
}
}
}
export default connect(mapStateToProps,mapDispatchToProps)(Index)
然后我找到这么一篇文章,
Why do we need middleware for async flow in Redux?
里面有个大佬的原话大概是:
- 为了更加贯彻
redux的思想 - 而且
react-thunk可以更好地调用getState
然后还修正了 action 必须是 pure 这段话,原话大概是:
I searched the Redux repo for clues, and found that Action Creators were required to be pure functions in the past.
This is incorrect. The docs said this, but the docs were wrong.
Action creators were never required to be pure functions.
We fixed the docs to reflect that.
如果理解有错,欢迎大佬斧正
边栏推荐
- kitti2bag 安装出现的各种错误
- Leetcode 176 The second highest salary (June 25, 2022)
- 项目部署遇到的问题-生产环境
- Literature reading --- optimize RNA SEQ research to study herbicide resistance (review)
- 少儿编程对国内传统学科的推进作用
- Group counting notes - instruction pipeline of CPU
- Utonmos: digital collections help the inheritance of Chinese culture and the development of digital technology
- 浅谈虚拟内存与项目开发中的OOM问题
- Question about SQL: SQL question -- SQL code for multiple account logins
- [system architecture] - how to evaluate software architecture
猜你喜欢

Using meta analysis to drive the development of educational robot

Kotlin quick start

Analysis of the multiple evaluation system of children's programming
![[reading papers] fbnetv3: joint architecture recipe search using predictor training network structure and super parameters are all trained by training parameters](/img/84/2b66b513a0a36464233708fbb4b57d.png)
[reading papers] fbnetv3: joint architecture recipe search using predictor training network structure and super parameters are all trained by training parameters

Analysis and optimization of ue5 global illumination system lumen

工业机器人之“慧眼”——机器视觉

On virtual memory and oom in project development

Authorization of database

给网站添加“开放搜索描述“以适配浏览器的“站点搜索“

UE5全局光照系统Lumen解析与优化
随机推荐
P2483-[模板]k短路/[SDOI2010]魔法猪学院【主席树,堆】
jupyter notebook的插件安装以及快捷键
On virtual memory and oom in project development
小米电视的网页和珠宝的网页
《你不可不知的人性》經典語錄
浅谈虚拟内存与项目开发中的OOM问题
XGBoost, lightGBM, CatBoost——尝试站在巨人的肩膀上
论文回顾:Unmixing-Based Soft Color Segmentation for Image Manipulation
2021-08-04
[hash table] a very simple zipper hash structure, so that the effect is too poor, there are too many conflicts, and the linked list is too long
Various errors in kitti2bag installation
经典模型——ResNet
校园创客空间的硬件造物原理
MySQL增删查改(进阶)
Translation notes of orb-slam series papers
Matlab| short term load forecasting of power system based on BP neural network
Arthas(阿尔萨斯) 能为你做什么?
Learn from Taiji makers - mqtt (V) publish, subscribe and unsubscribe
Preparation for wechat applet development
Une citation classique de la nature humaine que vous ne pouvez pas ignorer