Getting started with Redux 0x104: action creators

Time:2020-10-18

Overview of 0x000

It’s a bit tiring to write long articles. Write short articles occasionally

Concept of 0x001

In fact, many frameworks are not too difficult in technology. What is really difficult is the thought, and the breakthrough in thought is much more difficult than that in technology.reduxIt brings me a new idea of applying state management, which is full of many concepts,statereduceAfter a careful understanding of its ideas, it may be very simple,Action CreatorsIt’s one of them.

0x002 chestnut

Let’s see how we use it in the frontreduxOf:

import {createStore} from 'redux'
function counter(state = 0, action) {
    switch (action.type) {
        case 'INCREMENT':
            return state + 1
        default:
            return state
    }
}

let store = createStore(counter)

store.subscribe(() => {
    console.log(store.getState())
})

store.dispatch({type: 'INCREMENT'})

We usestore.dispatch({type: 'INCREMENT'})Sent out aactionHowever, this method is not elegant. There are two problems

  1. It is easy to generate duplicate code, especially complex codeaction
  2. Use string astypeError prone, refactoring is not easy (200 places usedINCREMENTOne day, it will be changed

For the second problem, the solution is very simple, just use constants

const ACTION_INCREMENT='INCREMENT'
store.dispatch({type: ACTION_INCREMENT})

The first problem, also very simple, use the function to pack up

const increment = () => {
    return {
        type: ACTION_INCREMENT
    }
}

store.dispatch(increment())

This encapsulated function isAction CreatorThis is just a function encapsulation. However, it has been greatly improved in terms of maintainability

  1. There is no need to write repeatedly{....}To prevent largeacitonWrite about vomiting
  2. Hide details when changing dynamically, asynchronouslyactionData assembly
const increment = (step) => {
    return {
        type: ACTION_INCREMENT,
        step:step
    }
}

store.dispatch(increment(5))

0x003 summary

When learning a thing, you can understand the concept through practice. The pure concept is a headache.

0x004 resource

  • Source code