So to sum up Redux.

What is the story?

Redux is a JavaScript state container that provides predictable state management. Speaking is used to share and use data when data usage is complicated in large projects. He stores all the data, known as state, in one object so that we can manage it all together.

Redux’s three principles:

  1. Single data source:

The data managed by Redux throughout the project should be stored by a store object. 2. Read-only state: A way to modify a Store object, only by dispath an action. Methods in the object, they just have getter methods, no setter methods. 3. Use pure functions to modify

For pure functions, my understanding is that if you take the same input to a function, you should get the same output:

Fn1 (1) // 1 fn1(2) // 2 fn1(1) // Now we evaluate again, if it's 1, it's pure, if it's not, it's not pureCopy the code

Therefore, it is best not to output methods such as array.push in modified values, which would change the value of the returned value without changing the address value, making Redux unmodifable

How Redux works

First introduce the following three swordsmen of Redux: Action, Store and Reducer. If Redux were a restaurant, the three musketeers would each have their own job:

  • Action: Mainly responsible for defining and creating various action event objects, so that the Store can call reducer through dispatch and treat it as the server of the whole Redux
  • Store: Mainly responsible for direct dialogue with components, use corresponding action methods by guiding various requirements conveyed by components, and then inform reducer to carry out corresponding operations. Can be the boss of the whole Redux
  • Reducer: Is mainly responsible for processing the data passed to it by the Store, and then callback the new data to the Store. It can be treated as the chef of Redux

This is Redux’s work I found online. As you can see, the three musketeers communicate data between the Redux and React components through their respective functions.

Redux code (not including react-redux parts)

Next, I’ll show you how to use redux without using react-Redux. We will use redux to store the React component. Let’s say I want to show the ShowTags component a bunch of data from Redux and use button to control whether to display it

Redux directory

Yarn Add redux first imports the redux library, and then creates a new directory under the SRC directory

  • src
      • redux
        • action
          • showTagsAction.js
        • reducer
          • showTagsReducer.js
        • store.js

        The next step is to write on the inside of each document

Const showTagsAction = (isShow)=>{return {type:"showTags",data:isShow} } export default showTagsAction -showTagsReducer showTagsReducer(preState=false,action){ const {type,data} = action switch (type){ case "showTags": return data default: return preState; }} -store.js // createStore is the core API, Use to create a redux import {createStore} from "redux" // Import the related reducer code import showTagsReducer from the reducer that was written in the reducer "./reducer/showTagsReducer"; Export default createStore(showTagsReducer)Copy the code

You can then write code in the showTags component

This is the code written inside the showTags component
import React, {Component} from 'react'; import store from ".. /.. /redux/store" import showTagsAction from ".. /.. /redux/action/showTagsAction"; Export Default Class Index extends Component {state = {tagsArr:[{id:"001",name:" 003 ",name:" 003 "}],isShow:true} // Attach a subscribe method to the store method when the component is mounted. ComponentDidMount () {store.subscribe(()=>{this.setState()=>{return {... this.state,isShow:! This.state. isShow}})})} // When the change state button is clicked, the function is triggered. ChangeState = ()=>{const {isShow} = this.state store.dispatch(showTagsAction(isShow))} render() { const {tagsArr} = this.state return ( <> <ul> {store.getState() ? tagsArr.map(item=><li key={item.id}>{item.name}</li>) : <button onClick={this.changeState}>change state</button> </ul> </>)}Copy the code
  • In this method, the following methods of the Store method are used altogether:
    • GetState: Gets the data stored in the store and displays it
    • Subscribe: Subscribes to a Store object that listens for changes to the React object when the component is mounted
    • Dispath: Causes the store object to send an action command to the reducer for operation

redux thunk:

Redux tends to be used for asynchronous operations on data, where we need to implement the code using the Redux-Thunk component. Let’s say we need a button to render the value on the page one minute after +1 is clicked:

const addNum = (num)=>{
    return {type:"addNum",state:num}
}

const addNumAsync = (num)=>{
    return (dispatch) => {
        setTimeout(() => {
            dispatch(addNum(num));
        }, 1000);
    };
}
export default addNumAsync;
Copy the code

If redux is used, the following error will be reported:

The reason for this error is that Redux can only accept a simple object and cannot handle objects like asynchrony. So, we need to bring in middleware to do everything possible in between. Here we use redux’s native API —-applyMiddleware, which requires passing in an array of middleware and executing the middleware functions in turn. We need a library to wrap asynchronous actions into enhanced actions that can be called by Dispath. Redux-thunk: Redux-thunk: redux-thunk: redux-thunk

import {applyMiddleware, createStore} from "redux";
import thunk from 'redux-thunk';
import appReducer from "./reducer/app_reducer";


export default createStore(appReducer,applyMiddleware(thunk))
Copy the code

At this point, the code can be run through, resulting in an asynchronous use method.

This is the basic method of using Redux. It can be seen that redux is inefficient. When the amount of data increases, the corresponding amount of code will also increase, and the number of listeners will also increase, making it difficult to write.