React tutorial Chapter 11 introduction and simple implementation of Redux



There is always a gap in component-based development of front-end framework cross component communication. I am hereVue tutorialAs mentioned in, if you don’t understand cross component communication, you can skip to it first.

React is different from bidirectional data binding framework. It is a one-way data flow, so it has to be called every time it is updatedsetStateSo it will be more circuitous in cross component communication. There is no logical layering in react. In the development process, logical layering is very important.

Redux realizes the benefits of cross component communication and logical layering, so it is more convenient to use Redux in react.

Simple implementation of Redux

To illustrate the problem, let’s start with a common object to realize cross component communication. Of course, this is also the implementation principle of flux.

export default {
        return {
            type: "+"
        return {
            type: '-'
export default (state = 0, action) => {
        case '+':
            return state + 1;
        case '-':
            return state - 1;
            return state;
import React, {Component} from 'react'
import {createStore} from 'redux'
import Actions from './actions'
import Reducer from './reducer'

const store = createStore(Reducer);

export default class Component1 extends Component{
        this.state = {count: 0}
    increment = () => {
            count: store.getState()
        return (
                <input type="button" value="increment" onClick={this.increment}/>

Summary – stratification

  • Actions layer

    • User behavior operation is triggered by user in view layerstore.dispatch(Actions.increment());
    • Behavior operation should be afunctionAnd must return atypeProperty
    • Each method should be managed bystoreDistribute.
  • Reducer layer

    • It must be a pure function (the return result of a function only depends on its parameters, and there are no side effects in the execution process)
    • Accept two parameters, the first isstateAnd the other isaction
    • returnThe results can be usedstore.getState()To receive
  • Store layer

    • reduxOne of the best ways is to acceptreducer, returns an objectstore
    • objectstoreHow to do itdispathFor distributionaction
    • adoptdispathDistributedactionWill triggerreducer
  • View layer

    • View layer, that is, component
    • adoptgetState()Get the value of thesetStateThen it can be displayed.