A quick hands-on experience of Redux + react Redux + examples

Time:2020-11-16

This paper mainly records the climbing process on the react road and provides some reference examples for the students who just learn redux.

It’s really comfortable to use Vue syntax sugar for a long time before, but now the company’s project is using react, so we have to silently switch from Vue to react. In fact, they are all similar frameworks. Although the syntax is quite different, there are still some places with similar ideas
This paper is mainly divided into two parts: Redux and react redux. First of all, let’s go through the basic part of redux

1.redux

You should know that Redux and react do not have a half dollar relationship. Redux can even be used with JQ. React Redux is the third-party plug-in for convenient operation of redux. Therefore, before learning react Redux, we should be familiar with the idea of redux. This article is more direct, not virtual, directly on the code:
First of all, I’m familiar with it
1 use of official scaffolding
create-react-app redux-demo

2. After setting up the environment, continue to install redux
npm install redux --S

Go into the project folder and delete everything that we can’t use

In SRC/ index.js We introduce Redux and create action reducer and store
src/index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { createStore } from 'redux' 
 
//This is the original state of redux
const tiger = 10000

//This is action
const increase = {
    Type: 'wage increase'
}
const decrease = {
    Type: 'deduction of wages'
}

//This is reducer
const reducer = (state = tiger, action) => {
    switch (action.type){
      Pay rise: 
        return state += 100;
      Case 'deduction': 
        return state -= 100;
      default: 
        return state;
    }
}

//Create store
const store = createStore(reducer);

console.log(store.getState())


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

Here is a general explanation of each of them
Action: behavior. It is an object that must have a type to specify its type. This type can be understood as what you want to do. The reducer should return different states according to the type of action. Each item has and can have multiple actions
Reducer: it can be understood that a factory dealing with state gives it an old data, which will be different according to different conditions action.type Return new data, that is: old state + action = new state, each item has and can have multiple reducers
Store: a store is essentially a state tree that holds the state of all objects. Any UI component can directly access the state of a specific object from the store. Each project has and can only have one store
With these basic concepts in mind, we can put the reducer in the create store and create the store

You can see at the end of the code that we printed store.getState () the simple understanding of this code is to print the data in the store
Because we only wrote the action and did not give it a dispatch, so the reducer only takes the default default, so it just returns state = tiger, and tiger is the state we defined before
At this time, NPM start opens the demo F12 in the browser and opens the console. You can see that the printed data is 10000
Here we just briefly review the basic knowledge of redux app.js Anything in it

OK, we can see that although we have defined action above, it doesn’t seem to be of any use? The next thing we need to do is change it.
Just now we just got the initial data, which is not the result we want. In the actual project, we must have a lot of requirements. Different requirements correspond to different functions, and different functions get different data. Therefore, we need to use dispatch to send different actions to it, and the code is as follows:
src/index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { createStore } from 'redux' 
 
const tiger = 10000

//This is action
const increase = {
    Type: 'wage increase'
}
const decrease = {
    Type: 'deduction of wages'
}
//This is reducer
const reducer = (state = tiger, action) => {
    switch (action.type){
      Pay rise: 
        return state += 100;
      Case 'deduction': 
        return state -= 100;
      default: 
        return state;
    }
}

//Create store
const store = createStore(reducer);

//Subscribe to events
store.subscribe(() =>
  console.log(store.getState())
);

//Distribution events
store.dispatch(increase)

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

As you can see, the printed data becomes 11000, that is to say, the reducer returns the new state according to the type of action dispatched by dispatch. Of course, we can also distribute them store.dispatch (decrease) the printed result is 10000, and the reason must be known to all.
In fact, we just wrote more store.dispatch (increase) and store.subscribe Each of their roles can be roughly explained as follows:
The function of dispatch is to tell the reducer that I will give you an action, and you should follow my action.type Returns the new state. Then, the reducer will return the new state according to the type of the action.
We give it the dispatch action, and the reducer makes the corresponding action. Finally, it returns the new state, but in fact, at this time console.log () the new data will not be printed because the state is still printed even though the state has changed store.getState () is still raw data
That’s when we need it store.subscribe (() = > {}) its function is that every time the reducer returns new data, it will automatically update the page and update the state of UI components. Otherwise, although the state changes, the page will not be updated (although there are no other components yet)

2.react-redux

Well, that’s the basic Redux knowledge. It’s not hard for us to find out. It’s really troublesome. You need to write a lot of things, and we haven’t separated reducer and action, otherwise I have to pass a lot of things to many components. This is very unfriendly to our actual development.
Therefore, the need for react Redux is very urgent. Its function is to help us operate redux. With it, we can easily write redux. Next, code:

First, install react redux

   `npm install react-redux --S`

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import { Provider, connect } from 'react-redux';

class App extends Component {
    render() {
        const { PayIncrease, PayDecrease } = this.props;
        return (
            <div className="App">
                <div className="App">
                    <h2>The salary of the month is{ this.props.tiger }</h2>
                    < button onclick = {payincrease} > promotion and salary increase
                    < button onclick = {paydecrease} > late fine
                </div>
            </div>
        );
    }
}

const tiger = 10000

//This is action
const increase = {
    Type: 'wage increase'
}
const decrease = {
    Type: 'deduction of wages'
}
//This is reducer
const reducer = (state = tiger, action) => {
    switch (action.type) {
        Pay rise:
            return state += 100;
        Case 'deduction':
            return state -= 100;
        default:
            return state;
    }
}

//Create store
const store = createStore(reducer);

//What data do you need to render
function mapStateToProps(state) {
    return {
        tiger: state
    }
}
//What behaviors need to be triggered
function mapDispatchToProps(dispatch) {
    return {
        PayIncrease: () => dispatch({ Type: 'wage increase' }),
        PayDecrease: () => dispatch({ Type: 'deduction of wages' })
    }
}

//Connecting components
App = connect(mapStateToProps, mapDispatchToProps)(App)

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('root')
)

As we can see, we’ve only made a few changes to the code in the index.js An app component is written to facilitate our observation. Buttons in the app component trigger different events.
Action, reducer and store must have been known by all of us, so we will not introduce it here. We mainly focus on where the changes are:
First of all, the most obvious is the introduction of react Redux provider and connect in demo. They are very important! Here is a brief explanation of their functions
Provider: it is a react component provided by react redux. Its function is to pass the state to all its sub components. That is to say, when you use the provider to input data, all the following sub components can share data, which is very convenient.
The usage of provider is: wrap the provider component in the outermost component, as shown in the code, wrap the entire app component, and then pass the store in the provider. Note: store must be transferred in provider, not in app component.
Connect: it is a high-level component. The so-called high-level component is that you pass in a component to it, and it will return you a new processed component. It is simple to pay attention to the usage, but it is difficult to study its principle. We don’t do a deep study of connect here, but we mainly learn how to use it. After all, if you want to go deep into it, you must first know how to use it. First of all, it has four parameters ([mapstatetoprops], [mapdispatchtoprops], [mergeprops], [options]). The latter two parameters can not be written. If they are not written, they have default values. We focus on the first two parameters, mapstatetoprops and mapdispatchtoprops.
Connect is used to connect the specified state and action with the react component, and write the UI component name in parentheses.

In addition, there are mapstatetoprops mapdispatchtoprops in the demo. What are their functions? In a popular way:
For example, if you are in a deep UI component, it is very difficult to get the data of the store. Mapstatetoprops is to tell the store which state you need and what data you need to write it directly in mapstatetoprops, and then the store will return it to you. Similarly, if you want to dispatch some behaviors, mapdispatchtoprops tells the store what behaviors you want to distribute and what behaviors need to be distributed in mapdispatchtoprops. Then the store will tell the reducer the behaviors you want to distribute, and then everyone should know that the reducer will return the new state according to the old state and action.

OK, at this time, let’s open the browser in NPM start to see what effect it has:
A quick hands-on experience of Redux + react Redux + examples

You can see that there is already content on the page. There is a paragraph of text and two buttons on the page. What will happen when we click it?
A quick hands-on experience of Redux + react Redux + examples
Sure enough, when we click the ‘promotion and salary increase’ button, the ‘salary of the month’ will also increase correspondingly. Let’s sort out the whole process
1. Click button 2 to trigger paydecrease() method 3. This method dispatches corresponding action 4. According to the type response of action, new state 5 is obtained{ this.props.tiger }Get the new state and render it to the page

OK, we will implement this simple demo. But now there is another problem: we write all the action reducer store provider connect on one page, which is certainly unreasonable in our actual development. Therefore, we will optimize the small demo at last
First of all, we need to extract the action and reducer as a separate file, and then export:
src/index.reducer.js:

const tiger = 10000

//This is action
const increase = {
    Type: 'wage increase'
}
const decrease = {
    Type: 'deduction of wages'
}
//This is reducer
const reducer = (state = tiger, action) => {
    switch (action.type) {
        Pay rise:
            return state += 100;
        Case 'deduction':
            return state -= 100;
        default:
            return state;
    }
}
export default reducer

Secondly, we should also write the app components on the outside (note here: the exported app components are not app components, but app components after connect)
src/APP.js:

import React, { Component } from 'react';
import { connect } from 'react-redux';

class App extends Component {

  componentDidMount() {
    console.log(this.props)
  } 
  render() {
    const { PayIncrease, PayDecrease } = this.props;
    return (
      <div className="App">
        <h2>The salary of the month is{ this.props.tiger }</h2>
        < button onclick = {payincrease} > promotion and salary increase
        < button onclick = {paydecrease} > late fine
      </div>
    );
  }
}
//What data do you need to render
function mapStateToProps(state) {
  return {
    tiger: state
  }
}
//What behaviors need to be triggered
function mapDispatchToProps(dispatch) {
  return {
    Payincrement: () = > dispatch ({type: 'wage increase'}),
    Paydecrease: () = > dispatch ({type: 'deduction of wages'})
  }
}

export default App = connect(mapStateToProps, mapDispatchToProps)(App)

After separating these things, the index.js It seems to be much simpler
src/index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import reducer from './index.reducer'

//Create store
const store = createStore(reducer);


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

Well, comparing the basic examples of Redux and react Redux is over here. I feel that there is a bit of nonsense.. All you can see is true love.. Where there are mistakes, welcome to correct!

Recommended Today

JS function

1. Ordinary function Grammar: Function function name (){ Statement block } 2. Functions with parameters Grammar: Function function name (parameter list){ Statement block } 3. Function with return value Grammar: Function function name (parameter list){ Statement block; Return value; } Allow a variable to accept the return value after calling the function Var variable name […]