当前位置:网站首页>Redux thunk simple case, advantages, disadvantages and thinking
Redux thunk simple case, advantages, disadvantages and thinking
2022-06-26 03:32:00 【A hug a song】
redux-thunk
Implement an asynchronous adder
The framework is : react
+ react-redux
+ redux-thunk
Project structure
The code is as follows
Create a new one component -> App.js
, The code is as follows
// 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
newly build services -> index.js
, The interface layer
export function getData(){
return Promise.resolve({
num:1})
}
Actions
newly build 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
newly build 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
Create a new one 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>
Current data {
props.state} <br></br>
<button onClick={
()=>{
props.add_count_sync()
}}> Click on the I </button>
</div>
}
const mapStateToProps = function(store) {
return {
state: store.count_change
}
}
export default connect(mapStateToProps,{
add_count_sync})(Index)
Redux-thunk Summary of advantages and disadvantages
advantage
- The code is simple and clear
- Small amount of library code
shortcoming
- Because the interface layer is called first , The resulting code may be particularly bloated , Imagine an example
If an interface needs to trigger action Of `A1` , It also needs to trigger `A2`,
This may make the interface need to determine which one needs to be triggered when it is asynchronous action , It makes the code hard to maintain
Add
Recently, I have seen some big guys blog, By the way react-thunk
Source code , Just a few very simple words , It's just one. Coriolis function
// 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 It's actually our dynamic 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
reflection
Here is a problem
, In fact, the appeal Method
no need react-thunk
, Can also be realized , There is no need to implement asyncAction
, and action
It's also 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)
Then I found this article ,
Why do we need middleware for async flow in Redux?
The original words of a big man in it are probably :
- In order to be more effective
redux
Thought - and
react-thunk
Can better callgetState
And then I corrected action
Must be pure
This passage , The original words are probably :
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.
If the understanding is wrong , Welcome to ax
边栏推荐
- 路由跳转之点击列表的操作按钮,跳转至另一个菜单页面并激活相应的菜单
- Stm32cubemx: watchdog ------ independent watchdog and window watchdog
- Tupu software is the digital twin of offshore wind power, striving to be the first
- Notes on the 3rd harmonyos training in the studio
- scrapy返回400
- 显卡、GPU、CPU、CUDA、显存、RTX/GTX及查看方式
- Qixia fire department carries out fire safety training on construction site
- 工业机器人之“慧眼”——机器视觉
- progress bar
- The "eye" of industrial robot -- machine vision
猜你喜欢
分割、柱子、list
Add an "open search description" to the site to adapt to the browser's "site search"“
[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
Authorization of database
【论文笔记】Learning to Grasp with Primitive Shaped Object Policies
计组笔记——CPU的指令流水
MySQL增删查改(初阶)
进度条
Components and routing
解析创客空间机制建设的多样化
随机推荐
工作室第3次HarmonyOS培训笔记
【论文笔记】Learning to Grasp with Primitive Shaped Object Policies
Double carbon bonus + great year of infrastructure construction 𞓜 deep ploughing into the field of green intelligent equipment for water conservancy and hydropower
开通基金账户是安全的吗?怎么申请呢
Vulhub replicate an ActiveMQ
Butterknife unbinder uses flashback in fragment and viewpager
Analysis on the diversification of maker space mechanism construction
stm32Cubemx:看门狗------独立看门狗和窗口看门狗
Network PXE starts winpe and supports UEFI and legacy boot
360 秒了解 SmartX 超融合基础设施
“再谈”协议
如何筹备一场感人的婚礼
Xiaomi TV's web page and jewelry's web page
多媒体元素,音频、视频
Notes on the 3rd harmonyos training in the studio
Interpreting Oracle
MySQL增删查改(初阶)
ArrayList#subList这四个坑,一不小心就中招
Is it safe to open a fund account? How to apply
On virtual memory and oom in project development