当前位置:网站首页>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
边栏推荐
- [system architecture] - how to evaluate software architecture
- UE5全局光照系统Lumen解析与优化
- scrapy返回400
- Graphics card, GPU, CPU, CUDA, video memory, rtx/gtx and viewing mode
- Leetcode 176 The second highest salary (June 25, 2022)
- Do you want to add a key to the applet or for sequence?
- Is it safe for individuals to buy stocks with flush software? How to buy stocks
- P2483-[template]k short circuit /[sdoi2010] Magic pig college [chairman tree, pile]
- 文献阅读---优化RNA-seq研究以研究除草剂耐药性(综述)
- 开通基金账户是安全的吗?怎么申请呢
猜你喜欢

Multimedia elements, audio, video

【读点论文】FBNetV3: Joint Architecture-Recipe Search using Predictor Pretraining 网络结构和超参数全当训练参数给训练了

Components and routing

校园创客空间的硬件造物原理

Partition, column, list

少儿编程对国内传统学科的推进作用

Using meta analysis to drive the development of educational robot

todolist未完成,已完成

Class diagram

Google recommends using kotlin flow in MVVM architecture
随机推荐
Drag and drop
浅谈虚拟内存与项目开发中的OOM问题
Cloud Computing Foundation -0
Is it safe for individuals to buy stocks with flush software? How to buy stocks
Is it safe to open an account in flush online? How to open a brokerage account online
USB驱动-debug
路由跳轉之點擊列錶的操作按鈕,跳轉至另一個菜單頁面並激活相應的菜單
Qt 中 deleteLater 使用总结
Xgboost, lightgbm, catboost -- try to stand on the shoulders of giants
Multimedia elements, audio, video
微信小程序开发准备工作
Google recommends using kotlin flow in MVVM architecture
【论文笔记】Deep Reinforcement Learning Control of Hand-Eye Coordination with a Software Retina
少儿编程对国内传统学科的推进作用
点击事件
进度条
Group counting notes - instruction pipeline of CPU
Golang regexp package use - 06 - other usage (Special Character conversion, find regular Common prefix, Switch gourmand mode, query regular Group NUMBER, query regular Group name, cut with regular, qu
解析少儿编程的多元评价体系
Scratch returns 400