当前位置:网站首页>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
reduxThought - and
react-thunkCan 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
边栏推荐
- UE5全局光照系統Lumen解析與優化
- Lumen Analysis and Optimization of ue5 global Lighting System
- The golang regular regexp package uses -06- other usages (special character conversion, finding the regular common prefix, switching greedy mode, querying the number of regular groups, querying the na
- 【读点论文】FBNetV3: Joint Architecture-Recipe Search using Predictor Pretraining 网络结构和超参数全当训练参数给训练了
- Is it safe for individuals to buy stocks with flush software? How to buy stocks
- HL7Exception: Can‘t XML-encode a GenericMessage. Message must have a recognized struct
- MySQL增删查改(进阶)
- Analysis and optimization of ue5 global illumination system lumen
- Upload file / text / picture, box shadow
- 丝网印刷的种类及其应用方法
猜你喜欢

分割、柱子、list

Click event

Graphics card, GPU, CPU, CUDA, video memory, rtx/gtx and viewing mode

请求对象,发送请求

Qt编译出错ERROR: Unknown module(s) in QT: script
![[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

ArrayList#subList这四个坑,一不小心就中招

Analysis on the diversification of maker space mechanism construction
随机推荐
“再谈”协议
Plug in installation and shortcut keys of jupyter notebook
Add an "open search description" to the site to adapt to the browser's "site search"“
Do you want to add a key to the applet or for sequence?
Components and routing
golang正则regexp包使用-06-其他用法(特殊字符转换、查找正则共同前缀、切换贪婪模式、查询正则分组个数、查询正则分组名称、用正则切割、查询正则字串)
小程序或者for循序要不要加key?
进度条
Notes on the 3rd harmonyos training in the studio
微信小程序开发准备工作
redux-thunk 简单案例,优缺点和思考
开通基金账户是安全的吗?怎么申请呢
360 秒了解 SmartX 超融合基础设施
progress bar
Gradient
Types and application methods of screen printing
kotlin快速上手
【读点论文】FBNetV3: Joint Architecture-Recipe Search using Predictor Pretraining 网络结构和超参数全当训练参数给训练了
Cliquez sur le bouton action de la liste pour passer à une autre page de menu et activer le menu correspondant
MySQL增删查改(初阶)