[React] Basic usage of react-redux (using connect function)

Article directory

      • 1.redux
      • 2.Install redux
      • 3.Operate redux
        • 3.1 Create the most core store
        • 3.2 Create a reducer that works for the store
        • 3.3 Responsive processing of redux
      • 4. Full version of redux
        • 4.1 Improve actionCreators
        • 4.2 thunk middleware
      • 5.react-redux
        • 5.1 Count container component
        • 5.2 connect function
        • 5.3 Provider

1.redux

redux schematic

  1. actionCreators: actionCreators is the first role that redux runs. It packages the content that the user wants to operate into an object, {key: value}, and into a {type: data}. type is the type of the operation, and data is the specific operation. value.
  2. Store: The store is the core role of redux. Although it accepts objects created by actionCreators, the essence is not handled by the store, but by the store to its reducers. After the reducer is processed, it is handed over to the store to save and update the state.
  3. reducers: The reducer is the worker that handles the status in the entire work of redux. The processing of the status is finally handed over to the reducer for processing.

2. Install redux

npm i redux

redux is not an official creation of react, but the combination of redux and react is more outstanding. You can even use redux to manage state in Vue and Angular, but in Vue, the Vue developer team has created a Vuex that is more suitable for Vue.

3. Operation redux

3.1 Create the most core store
import {<!-- -->createStore} from "redux"

export default createStore("Put reducer here")
3.2 Create a reducer that works for the store
import {<!-- -->INCREMENT, DECREMENT} from "../constant"

export default function countReducer(preState = 0, action) {<!-- -->
    const {<!-- -->type, data} = action
    switch (type) {<!-- -->
        case INCREMENT:
            return preState + data
        case DECREMENT:
            return preState-data
        default:
            return preState
    }
}

The first parameter is the original state, and the second parameter is the action object. The state needs to be initialized at the beginning, so the initial value of the specified state is 0.

3.3 Responsive processing of redux

Add redux monitoring to index.js.

ReactDOM.render(<App />, document.getElementById("root"));

store.subscribe(() => {<!-- -->
  ReactDOM.render(<App />, document.getElementById("root"));
});

4. Full version of redux

4.1 Improve actionCreators
import {<!-- -->INCREMENT,DECREMENT} from '../constant'

export const increment = data => ({<!-- -->type: INCREMENT, data})
export const decrement = data => ({<!-- -->type: DECREMENT, data})

export const asyncIncrement = (data, time) => {<!-- -->
    return dispatch => {<!-- -->
        setTimeout(() => {<!-- -->
            increment(data)
        }, time)
    }
}
4.2 thunk middleware

In redux we cannot make action a function, but based on thunk middleware we can redux support asynchronous functional actions.

npm i redux-thunk

store.js

import {<!-- -->createStore, applyMiddleware} from "redux"
import thunk from "redux-thunk"

export default createStore(countReducer,applyMiddleware(thunk))

5.react-redux

5.1 Count container component

The container component is the bridge between Count’s UI and redux. The container component gets the redux status and then passes it to the reactUI component through the props method. If the UI component wants to modify the status, it is also handed over to redux for processing through the container component.

import React, {<!-- -->Component} from "react";
import {<!-- -->connect} from "react-redux";
import {<!-- -->
    increment,
    decrement,
    asyncIncrement,
} from "../../actions/count";

class Count extends Component {<!-- -->
    increment = () => {<!-- -->
        const {<!-- -->value} = this.selectNumber;
        this.props.increment(value * 1);
    };

    decrement = () => {<!-- -->
        const {<!-- -->value} = this.selectNumber
        this.props.decrement(value * 1)
    }

    render() {<!-- -->
        return (
            <div>
                <h2>I am the Count component, and the total number of people in the component below is: {<!-- -->this.props.personCount}</h2>
                <h4>The current sum is: {<!-- -->this.props.count}</h4>
                <select ref={<!-- -->(c) => (this.selectNumber = c)}>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                </select>
                 &nbsp;
                <button onClick={<!-- -->this.increment}> + </button>
                 &nbsp;
                <button onClick={<!-- -->this.decrement}>-</button>
                 &nbsp;
                {<!-- -->/*<button onClick={this.incrementIfOdd}>The current sum is odd and plus it</button>*/}
                {<!-- -->/* & amp;nbsp;*/}
                <button onClick={<!-- -->this.asyncIncrement}>Asynchronous addition</button>
                 &nbsp;
            </div>
        );
    }
}

// mapStateToProps mapDispatchToProps
export default connect(
    (state) => ({<!-- -->
        count: state.count,
        personCount: state.person.length,
    }),
    {<!-- -->increment, decrement, asyncIncrement}
)(Count);
5.2 connect function

react-redux provides us with this function to build container components and then build bridges. Connect uses the function’s rationalization technology to transfer redux status and operation status methods to UI components.

mapStateToProps is the first parameter, mapDispatchToProps is the second parameter. Provide redux status and operation status methods for UI components. Provide operation status methods.

5.3 Provider

react-redux provides us with a tag that provides a store for future generations.

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import {<!-- --> Provider } from 'react-redux'
import store from "./redux/store";

ReactDOM.render(
    <Provider store={<!-- -->store}>
        <App/>
    </Provider>,
    document.getElementById("root")
);

In the previous redux, you needed to add subscribe manually. Because the underlying layer of react-redux has special processing, it is no longer needed.