Understand the initial use of redux in react in one article

Understand the initial use of redux in react in one article

Redux is a data state management plug-in. When using React or Vue to develop componentized SPA programs, sharing information between components is a very big problem. For example, after the user logs in, the client will store the user information (ID, avatar, etc.), and many components of the system will use this information. When using this information, it is very troublesome to retrieve it again every time. Therefore, each system needs a function to manage the common information used by multiple components. This is the role of redux.

If you are a developer who has never been exposed to redux, I hope you can take a look at it patiently. I am also optimistic about many blogs and slowly summarize them myself! ! ! ! It's better than the big guys looking for them one by one.

import React, { Component, Fragment } from 'react';

//Class importimport { connect } from 'react-redux';

//Hook import { useSelector, useDispatch } from 'react-redux'

import { add, clear } from '../../redux/actions/count';


//hook display component const CountItem = (props) => {
    // Deconstruct const {
        count,
        flag,
        add,
        clear
    } = props
    return (
        <>
            <h2>Current sum: {count}</h2>
            <h3>Current Flag: {flag ? 'true' : 'false'}</h3>
            <button onClick={add}>Click +1</button>
            <button onClick={clear}>Clear</button>
        </>
    )
}

//hook container component const Count = () => {
    const count = useSelector(state => state.sum)
    const flag = useSelector(state => state.flag)
    const dispatch = useDispatch()

    const countAdd = () => {
        console.log(add.type)
        dispatch(add(1))
    }

    const clearNum = () => {
        dispatch(clear())
    }

    return <CountItem count={count} flag={flag} add={countAdd} clear={clearNum} />
}

export default Count



// class display component // class Count extends Component {
// add = () => {
// // Notify redux
// this.props.add(1);
// };
// clear = () => {
// this.props.clear();
// };
// render() {
// return (
// <Fragment>
// <h2>The current sum is: {this.props.count}</h2>
// <h3>Current Flag: {this.props.flag ? 'true' : 'false'}</h3>
// <button onClick={this.add}>Click +1</button>
// <button onClick={this.clear}>clear</button>
// </Fragment>
// );
// }
// }

// class container component // export default connect(
// // 1. State// state => ({ count: state.sum, flag: state.flagState }),
// // 2. Methods // { add, clear }
// )(Count);

The basic usage is almost like this. The key method we use on hook is to use the state of redux with useSelector and to call reduce with dispatch; in the class component, connect is used to associate the state with the method (reduce).

The difficulty here lies in reduce and state

What is reduce here?

In the above code, we used the add and clear methods. We create a new js file to implement these two methods.

// Create an action object for the Count component // Import constants import { ADD, CLEAR } from '../constant';

// Create a function to add an action object export const add = data => ({
    type: ADD,
    data,
});

// Create a function to clear the action object export const clear = data => ({
    type: CLEAR,
    data,
});

There are constants above - this is to facilitate the unified management of actionType. Creating corresponding action objects helps modularize the code.
Paste it, create a constant.js and put it in

export const ADD = 'add';
export const CLEAR = 'clear';

At this point our action object is almost defined, and we need to manage the reducer. That is, dispatch distributes the above action objects to implement state updates

In the reducer folder we define a count.js

// Create a reducer for the Count component
// reducer receives two parameters: preState of the previous state, action object action

import { ADD, CLEAR } from '../constant.js';

// Set the initial state const initState = 0;

export default function addReducer(preState = initState, action) {
    // Get type and data from action
    const { type, data } = action;
    //Decide how to process data based on type switch (type) {
        case ADD:
            return preState + data;
        case CLEAR:
            return 0;
        // Initialization action default:
            return preState;
    }
}

The above method needs to use dispatch to call the type distribution (emphasis added)

The use is complete here. Next, let's configure redux to the react project.

There is no need to narrate in reverse order here, because it does not make sense.
Here are some key configurations
Configuration of store.js and use of global store

First look at the global use of store
Wrap App with Provider below your root route.

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
import store from './redux/store';
import { Provider } from 'react-redux';

ReactDOM.render(
    // Provider wraps App, purpose: to allow all descendant container components of App to receive store
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('root')
);

There is a redux/store.js here. See the code

// The entire document has only one store object. createStore receives two parameters, the first is the state tree, and the second is the action to be processed.
//applyMiddleware aggregates all middleware into an array and executes them in sequence, asynchronously processing import { createStore, applyMiddleware } from 'redux';
//Middlewareimport thunk from 'redux-thunk';
//Summarize all reducers
import allReducers from './reducers/index';
//Here is Google's debugging tool, specific usage: Baidu import { composeWithDevTools } from 'redux-devtools-extension';

// Expose the store
export default createStore(allReducers, composeWithDevTools(applyMiddleware(thunk)));

This article is coming to an end here. I still don’t understand some of the execution processes and principles in it. I still need to consolidate and learn more in the future.

The above is the detailed content of this article on how to use redux in react. For more information about using redux in react, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed explanation of the usage and principle analysis of connect in react-redux
  • Detailed explanation of JavaScript state container Redux
  • Explanation of the working principle and usage of redux

<<:  How to deploy egg applications on self-built Windows servers (with pictures and text)

>>:  MySQL SHOW PROCESSLIST assists in the entire process of troubleshooting

Recommend

How to install PHP7.4 and Nginx on Centos

Prepare 1. Download the required installation pac...

Disabled values ​​that cannot be entered cannot be passed to the action layer

If I want to make the form non-input-capable, I se...

Detailed explanation of the use of Vue3 state management

Table of contents background Provide / Inject Ext...

Detailed explanation of how to exit Docker container without closing it

After entering the Docker container, if you exit ...

Two ways to use react in React html

Basic Use <!DOCTYPE html> <html lang=&qu...

Similar to HTML tags: strong and em, q, cite, blockquote

There are some tags in XHTML that have similar fu...

Solution to span width not being determined in Firefox or IE

Copy code The code is as follows: <html xmlns=...

How to correctly create MySQL indexes

Indexing is similar to building bibliographic ind...

Detailed explanation of JDBC database link and related method encapsulation

Detailed explanation of JDBC database link and re...

How to use Docker to build a development environment (Windows and Mac)

Table of contents 1. Benefits of using Docker 2. ...

HTML tag ID can be a variable

<table id=" <%=var1%>">, the...

Example sharing of anchor tag usage in HTML

Anchor tag usage: Linking to a specific location i...

How to use Vue3 asynchronous data loading component suspense

Table of contents Preface Creating Components Sum...

Detailed explanation of JavaScript object conversion to primitive value

Table of contents Object.prototype.valueOf() Obje...