当前位置:网站首页>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.
如果理解有错,欢迎大佬斧正
边栏推荐
- Leetcode 176 The second highest salary (June 25, 2022)
- 工作室第3次HarmonyOS培训笔记
- Types and application methods of screen printing
- Lumen Analysis and Optimization of ue5 global Lighting System
- [system architecture] - how to evaluate software architecture
- 云计算基础-0
- Google recommends using kotlin flow in MVVM architecture
- Is it safe to open a fund account? How to apply
- Leetcode 175 Combine two tables (2022.06.24)
- 路由跳轉之點擊列錶的操作按鈕,跳轉至另一個菜單頁面並激活相應的菜單
猜你喜欢

Kotlin quick start

Click event

如何筹备一场感人的婚礼

stm32Cubemx:看门狗------独立看门狗和窗口看门狗

How Inkscape converts PNG pictures to SVG pictures without distortion

栖霞消防开展在建工地消防安全培训

Group counting notes - instruction pipeline of CPU

请求对象,发送请求

Xgboost, lightgbm, catboost -- try to stand on the shoulders of giants

The "eye" of industrial robot -- machine vision
随机推荐
Cliquez sur le bouton action de la liste pour passer à une autre page de menu et activer le menu correspondant
progress bar
Oracle connectivity issues and Solutions
力扣(LeetCode)175. 组合两个表(2022.06.24)
[solution] the blue screen restart problem of the virtual machine started by the VMware of Lenovo Savior
Route jump: click the operation button of the list to jump to another menu page and activate the corresponding menu
请求对象,发送请求
如何筹备一场感人的婚礼
Overview of orb-slam3 paper
少儿编程对国内传统学科的推进作用
工作室第3次HarmonyOS培训笔记
[hash table] improved, zipper hash structure - directly use two indexes to search, instead of hashing and% every time
数字孪生智慧水务,突破海绵城市发展困境
拖放
[QT] custom control - switch
Classic quotations from "human nature you must not know"
【论文笔记】Deep Reinforcement Learning Control of Hand-Eye Coordination with a Software Retina
小米电视的网页和珠宝的网页
Group note data representation and operation check code
解析社交机器人中的技术变革