当前位置:网站首页>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

 Insert picture description here

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

  1. The code is simple and clear
  2. Small amount of library code

shortcoming

  1. 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 :

  1. In order to be more effective redux Thought
  2. and react-thunk Can better call getState

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

原网站

版权声明
本文为[A hug a song]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206260306366739.html