当前位置:网站首页>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.
如果理解有错,欢迎大佬斧正
边栏推荐
- Upload file / text / picture, box shadow
- 个人用同花顺软件买股票安全吗?怎么炒股买股票呢
- [hash table] improved, zipper hash structure - directly use two indexes to search, instead of hashing and% every time
- What can Arthas do for you?
- 解析创客空间机制建设的多样化
- 【QT】自定义控件-空气质量仪表盘
- Authorization of database
- 显卡、GPU、CPU、CUDA、显存、RTX/GTX及查看方式
- Google recommends using kotlin flow in MVVM architecture
- 微信小程序开发准备工作
猜你喜欢
随机推荐
Problems encountered in project deployment - production environment
Translation notes of orb-slam series papers
Lumen Analysis and Optimization of ue5 global Lighting System
kitti2bag 安装出现的各种错误
Types and application methods of screen printing
Using meta analysis to drive the development of educational robot
GStreamer allocator and pool
P2483-[模板]k短路/[SDOI2010]魔法猪学院【主席树,堆】
计组笔记 数据表示与运算 校验码部分
ArrayList # sublist these four holes, you get caught accidentally
Overview of orb-slam3 paper
progress bar
[solution] the blue screen restart problem of the virtual machine started by the VMware of Lenovo Savior
论文回顾:Unmixing-Based Soft Color Segmentation for Image Manipulation
拖放
MySQL增删查改(进阶)
分割、柱子、list
如何筹备一场感人的婚礼
golang正则regexp包使用-06-其他用法(特殊字符转换、查找正则共同前缀、切换贪婪模式、查询正则分组个数、查询正则分组名称、用正则切割、查询正则字串)
路由跳转之点击列表的操作按钮,跳转至另一个菜单页面并激活相应的菜单








