Home Web Front-end JS Tutorial How to understand redux

How to understand redux

Sep 28, 2017 am 09:05 AM
redux how understand

Redux Principle

A company has three businesses: logistics (actionType), e-commerce (actionType), and advertising (actionType) , the funds earned from the three businesses are uniformly recorded in the company's financial system (state). One day, the e-commerce business sold 1 million worth of goods (actions) on the company's e-commerce platform. The funds earned were sent to the business's financial department in the form of invoices (dispatch). The financial department calculated the earnings through its own business blocks. The profit obtained (reducer) is then updated to the financial system (state).

Core principle: Through an event action, the results are sent to the reducer through dispatch. In the reducer, different business processes are performed on the data according to different actionTypes, and then the final results are updated into the state tree.

Since several of my bosses keep a close eye on the company's funds and must always pay attention to changes in funds, they set up an event (subscribe) to send a text message to notify them (listener) when there is a change in funds.

Principle: Redux has a built-in listeners array that allows external subscriptions to state data change events. When the data in the state tree changes, all listening events will be notified.

API explanation


function createStore(reducer, preloadedState, enhancer)
Copy after login

In the createStore method, the entire redux environment is initialized. preloadedState serves as the initial value of the state tree. This method returns the open interface of redux, and the state of redux can only be operated through the returned api.

CreateStore returns the returned API:


##

 return {
    dispatch,
    subscribe,
    getState,
    replaceReducer,
    [$$observable]: observable
  }
Copy after login

store.getState: Returns the state object currently maintained by redux;

store.subscribe : You can register subscription events through this interface, that is, when the state of redux is accessed (regardless of whether the data in the state is modified or not), redux will traverse all registered events.


function subscribe(listener) {
    if (typeof listener !== 'function') {
      throw new Error('Expected listener to be a function.')
    }

    let isSubscribed = true

    ensureCanMutateNextListeners()
    nextListeners.push(listener)

    return function unsubscribe() {
      if (!isSubscribed) {
        return
      }

      isSubscribed = false

      ensureCanMutateNextListeners()
      const index = nextListeners.indexOf(listener)
      nextListeners.splice(index, 1)
    }
  }
Copy after login

Store.dispatch: After the event action is run, push the results to the reducer through dispatch. The result of the action must be an ordinary js object, and must contain a type attribute. In the reducer, the data can be processed differently based on the type, and then updated to the corresponding state.

After the reducer, all listening events will be traversed regardless of whether the data has changed or not.


function dispatch(action) {
    if (!isPlainObject(action)) {
      throw new Error(
        'Actions must be plain objects. ' +
        'Use custom middleware for async actions.'
      )
    }

    if (typeof action.type === 'undefined') {
      throw new Error(
        'Actions may not have an undefined "type" property. ' +
        'Have you misspelled a constant?'
      )
    }

    if (isDispatching) {
      throw new Error('Reducers may not dispatch actions.')
    }

    try {
      isDispatching = true
      currentState = currentReducer(currentState, action)
    } finally {
      isDispatching = false
    }

    const listeners = currentListeners = nextListeners
    for (let i = 0; i < listeners.length; i++) {
      const listener = listeners[i]
      listener()
    }

    return action
  }
Copy after login
The entire single-page application only needs to call the createStore method once, and then ensure that the initialized object is globally available, so as to achieve unified management of data through redux.

The above is the detailed content of How to understand redux. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is there a future for employment in clinical pharmacy at Harbin Medical University? (What are the employment prospects for clinical pharmacy at Harbin Medical University?) Is there a future for employment in clinical pharmacy at Harbin Medical University? (What are the employment prospects for clinical pharmacy at Harbin Medical University?) Jan 02, 2024 pm 08:54 PM

What are the employment prospects of clinical pharmacy at Harbin Medical University? Although the national employment situation is not optimistic, pharmaceutical graduates still have good employment prospects. Overall, the supply of pharmaceutical graduates is less than the demand. Pharmaceutical companies and pharmaceutical factories are the main channels for absorbing such graduates. The demand for talents in the pharmaceutical industry is also growing steadily. According to reports, in recent years, the supply-demand ratio for graduate students in majors such as pharmaceutical preparations and natural medicinal chemistry has even reached 1:10. Employment direction of clinical pharmacy major: After graduation, students majoring in clinical medicine can engage in medical treatment, prevention, medical research, etc. in medical and health units, medical research and other departments. Employment positions: Medical representative, pharmaceutical sales representative, sales representative, sales manager, regional sales manager, investment manager, product manager, product specialist, nurse

In-depth understanding of how to use Linux pipelines In-depth understanding of how to use Linux pipelines Feb 21, 2024 am 09:57 AM

In-depth understanding of the use of Linux pipes In the Linux operating system, pipes are a very useful function that can use the output of one command as the input of another command, thereby conveniently realizing various complex data processing and operations. A deep understanding of how Linux pipes are used is very important for system administrators and developers. This article will introduce the basic concepts of pipelines and show how to use Linux pipelines for data processing and operations through specific code examples. 1. Basic concepts of pipes in Linux

React Redux Tutorial: How to use Redux to manage front-end state React Redux Tutorial: How to use Redux to manage front-end state Sep 26, 2023 am 11:33 AM

ReactRedux Tutorial: How to Manage Front-End State with Redux React is a very popular JavaScript library for building user interfaces. And Redux is a JavaScript library for managing application state. Together they help us better manage front-end state. This article will introduce how to use Redux to manage state in React applications and provide specific code examples. 1. Install and set up Redux First, we need to install Re

Understand the importance of Go language comments Understand the importance of Go language comments Mar 29, 2024 pm 04:48 PM

Comments are a very important part of Go programming. Comments can help programmers better understand the logic, purpose, and details of the code, thereby improving the readability and maintainability of the code. This article will introduce the importance of comments in the Go language, and combine it with specific code examples to illustrate how comments help code understanding. First, let's look at a simple Go program example: packagemainimport "fmt" funcmain(){/

How to correctly understand value passing in PHP How to correctly understand value passing in PHP Mar 08, 2024 pm 03:30 PM

How to correctly understand the value passing method in PHP PHP is a scripting language widely used in Web development, and the parameter passing methods in PHP mainly include value passing and reference passing. And understanding how values ​​are passed in PHP is crucial to writing efficient code. This article will discuss the value passing method in PHP in detail and use specific code examples to help readers better understand. The basic concept of value passing method is to copy the value of a variable and pass it to a function or method. Operations on the value within the function will not affect it.

In-depth understanding of the strings.Split function in Go language documentation In-depth understanding of the strings.Split function in Go language documentation Nov 04, 2023 pm 01:14 PM

To deeply understand the strings.Split function in the Go language documentation, specific code examples are required. In the Go language, string operations are a very common requirement. Among them, the strings package is a standard package provided by the Go language and provides a wealth of string processing functions. Among them, the strings.Split function is one of the commonly used functions. Its function is to split a string into a string slice according to the specified delimiter. Before we officially dive into the strings.Split function,

How to download win10 image quickly How to download win10 image quickly Jan 07, 2024 am 11:33 AM

Recently, some friends reported how to download win10 image files. Because there are so many image files on the market, what should I do if I want to find a regular file to download? Today, the editor has brought you the link to download the image and the detailed solution steps. Let’s take a look at them together. win10 image quick download and installation tutorial download link >>> System Home Ghostwin101909 image 64-bit version v2019.11<<<>>>Win10 image 64-bit v2019.07<<<>>>Win10 image 32-bit v2019.07<< <1. Search through the Internet

How to clean temp folder How to clean temp folder Feb 22, 2024 am 09:15 AM

How to clean the temp folder As we use the computer, temporary files (temp files) will gradually accumulate. These temporary files are generated when we use the computer, such as cache files when browsing the web, temporary files during software installation, etc. Failure to clean the temp folder for a long time may occupy a large amount of disk space and affect the speed of the computer. Therefore, cleaning the temp folder regularly is a necessary step to maintain computer performance. Below, we will introduce some simple ways to clean the temp folder. Method 1: Manually clean t

See all articles