With the Basics of React, I’m sure you have a good understanding of React and can create some simple React projects (note that I’m talking about simple projects here). Why can you only make simple projects? React is a simple, lightweight view layer framework.

Component communication and state management in React are particularly cumbersome. For example, a child component communicates with a parent component to change values through the parent component’s method. It’s like being in love. First you meet a girl, then you hold hands, then you kiss, then you do whatever you want. This kind of form is certainly not in line with people’s habits, so there are a lot of fast food service, overnight service, greatly convenient for the needs of modern people. Similarly, in development, the most important thing for companies is efficiency, which requires simplifying things. React is definitely not suitable for large-scale projects and rapid development. You need a view-layer framework plus a data-layer framework, and the two can be combined to achieve large development projects.

Redux is currently the best data layer framework in the React ecosystem, so a separate article is presented to systematically explain Redux.

The blogger is untalented and uneducated. If he does not guarantee the knowledge, please correct him. I will be careful to verify and ensure the correct knowledge.

Target 1000 free videos, 339 have been completed. (List of 339 front-end videos)

React Basics If you’re not familiar with React basics, learn the basics of React:

P0 :React Basics

(1.5x New World)

  1. React Introduction (315)

  2. React vs. Vue (314)

  3. React Development Environment (313)

  4. Introduction to the Project Catalog generated by scaffolding (312)

  5. HelloWorld and Components (311)

  6. React JSX syntax introduction

  7. React Instance – Little Sister Service Menu (309)

  8. React instance – A good sword grind, a good theory (308)

  9. React instance – Boss I need to add a clock

  10. React instance – The sword is too old to bear (306)

  11. React Advanced -JSX anti-tread pit (305)

  12. React Advanced -Simple React Snippets(304)

  13. React Advanced – Components Split (303)

  14. React Advanced – Parent and child components pass values (303)

  15. React Advanced – Monomial Data Streams and Others (302)

  16. React Advanced – Install and Use the React Debugging tool (301)

  17. React Advanced PropTypes check pass value (300)

  18. React-advanced ref (299)

  19. React Advanced – Life Cycle Tutorial -1(298)

  20. React Advanced – Life Cycle Introduction -2(297)

  21. React Advanced – Life Cycle Tutorial -3(296)

  22. React Advanced – Lifecycle Improvements to Application Performance (295)

  23. React Advanced – Axios Data Requests (294)

  24. React Advanced -Axios Request EasyMock(293)

  25. React Advanced – CSS3 React Animation (292)

  26. React Advanced -CSS3 KeyFrames animation (291)

  27. The React senior – React – the transition – group (290).

  28. React Advanced – MultiDOM Animation and Writing (289)

P0 :Redux (24 Episodes)

  1. Basics – Understanding Redux and Introduction to articles (339)

  2. Basics -Redux Workflow (338)

  3. Introduction to Ant Design and Environment Initialization (337)

  4. Making A UI with Ant Design (336)

  5. Create a Repository in Redux – Store and Reducer (335)

  6. Basic -Redux Dev Tools Installation (334)

  7. Basics – Experiencing Redux’s Flow through Input (333)

  8. Basics -Redux making ToDoList Lists (332)

  9. Basic – Delete ToDoList with Redux (331)

  10. Basics – Tips for Writing Redux at Work -1(330)

  11. Basics – Tips for Writing Redux at Work -2(329)

  12. Refill -Redux fills three pits (328)

  13. Advanced – Split component UI and Business logic (327)

  14. Advanced – Stateless components in Pit filling and Redux (326)

  15. Advanced -Axios asynchronously retrieves data and combines it with Redux (325)

  16. Installation and Configuration of advanced – Redux-Thunk Middleware (324)

  17. Use of advanced Redux-thunk (323)

  18. Advanced – Installation and Configuration of Redux-Saga (322)

  19. Advanced – Get TodoList list with Redux-saga (321)

  20. React-redux Introduction and Installation (320)

  21. React-redux Provider and Connect (319)

  22. Advanced -React-redux data modification (318)

  23. React-redux add List data (317)

  24. React-redux program Optimization (End)

Here’s a basic outline of what you can learn about the course.

P01: Basics – Understanding Redux and article introduction

In fact, the search for this article proves that you have a basic understanding of Redux. This article is suitable for beginning front-end developers to read. It will explain the basics of Redux in detail, and once you understand the basics, you will gradually add advanced Redux content.

The content of the course is based on React and Redux, but it is rearranged and added with its own understanding. If the author has any objection or request to delete it, please contact the blogger.

To introduce myself

Lots of old friends and some new friends. So let me introduce myself first. I have been making programs for more than 11 years under the online name “Tech Fat”. I have not made any world-changing products, and I am not an expert in any field. I’ve been blogging for the last two years with the goal of producing 1000 free videos to help newcomers to the front-end application. At present, I am a programmer who moves bricks every day. I love my current job and dream of becoming a full-time lecturer, and I have been working hard for my dream.

I do about three free front-end videos a week, so you can always learn along with me.

If you would like to learn React with the tech guy, you can enter the QQ group: 159579268

Redux introduces

Redux is a JavaScript application for managing data state and UI state. With the increasing complexity of JavaScript single page application (SPA) development, JavaScript needs to manage more states than ever before, and Redux makes it easier to manage. (Redux supports React, Angular, jQuery, and even pure JavaScript)

You can see how Redux simplifies state management by looking at a picture (the picture is from the “front-end record” website, if there is any infringement, please contact delete).

As you can see from the figure, passing state without Redux is cumbersome. In Redux, data can be stored in a data warehouse (store-common state storage space), where state can be centrally managed, and which components use stroe to find the state. If a purple component in transit wants to change its state, all it needs to do is change the state in store, and the rest of the components will automatically follow suit.

Flux and Redux

A lot of friends will ask me whether to talk about Flux. Here I can give you a clear answer, no.

In my opinion, Redux is an upgraded version of Flux. In the early use of React, Flux was used for state management. However, in the use of React, Flux revealed many disadvantages, such as the complexity and error-prone of multi-state management. So Redux was born, and has now completely replaced Flux, leaving the old stuff behind.

If you say that the company is still using Flux, you can try to learn Redux, upgrade and discard Flux. In fact, the front-end knowledge is updated so quickly, so keep learning the habit.

The update frequency

I’m also a programmer. I have to work every day, and I have to work overnight, so I update about three episodes a week. Join the QQ group to get the latest information in the first time. Let’s study together.

P02: Base-Redux workflow

The knowledge learned in this lesson is so important that you will have a thorough understanding of Redux until you understand the Redux workflow. If you only use the official image or look at the documentation, it’s a little difficult. But if you have a lot of social contacts or are like Chubby, a big sister lover, then the process is easy. (Watch video)

Redux official image

First take a look at the official picture, I also try to explain, not blame. Because this thing is not very easy to understand, the official is very abstract.

And the interpretation of this, if you look at the video, is a bit of a pain to write. In fact, I think this diagram is completely from the perspective of someone who has been to Redux, or at least a beginner of Redux, not from the perspective of a beginner.

I drew the understanding diagram

I will explain this diagram to you as an experienced driver for many years. You can completely understand this diagram as the process of a big sword. If you are not experienced, or you are a girl, I can understand it as the process of borrowing books. Of course I’ll take the sword as an example (I drew it myself and it’s ugly).

React Components is like a great official. Then we came up with “Great Sword,” and we met With Action Creators, “Momsan.” We said, “I want to find Xiao Hong.” Mother Sang returned to the Store and then asked Reducer to see if “Red” is busy (current state), if not, let her come and match the senior official.

I also have a librarian version for girls and inexperienced children.

And I’m going to do that in the video, so I’m not going to write too much about it.

Summary: The implementation of Redux is simple, but if you look at the official image and it’s hard to understand, you can relate it to what’s going on around you and make it a lot easier. In particular, it is important that you understand this workflow for your Redux learning.

P03: basic –Ant DesignIntroduction and environment initialization

Ant Design is a UI framework for enterprise development that works well visually and dynamically. It supports not only React, but also ng and Vue versions. I think Ant Design is a good choice for any front-end framework you use. It is customary to abbreviate AntDesign to ANTD. Currently, there are approximately 50,000 stars, which is the largest in the React UI framework.

Website is: ant. The design/index – cn

Initialize the project

By default, you’ve already seen my “React16 Free video tutorial”, so I assume you’ve got the point, and I’m just going to walk you through it.

  1. If you don’t have a scaffolding tool, you will need to:
npm install -g create-react-app
Copy the code
  1. Create the project directly with the scaffolding tool
D: // Create the ReduxDemo folder CD ReduxDemo // create the ReduxDemo folder creation-react-app demo01 // create the React project CD demo01 // After the project is created, go to the project directory NPM start // preview the projectCopy the code

Now that the project is done, let’s delete unnecessary files and keep the code structure minimal. Delete all files in SRC except index.js, and empty all files in index.js.

Quick generation of basic code structure

Write index.js file, this file is a basic file, basic code is the same.

import React from 'react';
import ReactDOM from 'react-dom'
import TodoList from './TodoList'

ReactDOM.render(<TodoList/>.document.getElementById('root'))
Copy the code

Write a todolist.js file that can be quickly generated with Simple React Snippets. Enter IMRC and then CCC

The code is as follows:

import React, { Component } from 'react';
class TodoList extends Component {
    render() { 
        return ( 
            <div>Hello World</div>); }}export default TodoList;
Copy the code

Once this is done, the project is basically built, and you can open your browser to see what it looks like. Now you are ready to install the Ant DesignUI framework.

The installationAntDesign

NPM is used here to install, of course you can use YARN to install.

npm install antd --save
Copy the code

Yarn can be installed as follows:

yarn add antd
Copy the code

If your network condition is not good, it is best to use CNPM to install. After waiting for the program installation, you can use it. My home network took a long time to set up, so I’ll wait until the next lesson to learn how to use it.

P04: Basic – useAnt DesignMaking the UI

You have completed the installation of the basic development environment and AntDesign. In this lesson, we will use Ant Design to create the TodoList interface. This article will not cover Ant Design in depth, just to make the course’s interface better. If you have a strong need or desire to learn about Ant Design, you can take a look at the official Ant Design documentation, which is in Chinese. The picture is what we’re going to do at the end of the lecture.

Introducing CSS styles

When using Ant Design, the first thing you do is introduce CSS styles that make your UI components look good. You can import import directly in the/SRC/todolist.js file.

import 'antd/dist/antd.css'
Copy the code

Write the Input box

After introducing CSS styles, you can happily use the box in ANTD. To use it, you need to introduce the input component first. The full code is as follows:

import React, { Component } from 'react';
import 'antd/dist/antd.css'
import { Input } from 'antd'

class TodoList extends Component {
    render() { 
        return ( 
            <div>
                <div>
                    <Input placeholder='jspang' style={{ width:'250px'}} / >
                </div>
            </div>); }}export default TodoList;

Copy the code

In the Input component, we set the style. Note that we do not set this with single or double quotes.

Once you’re done, you can simply look at the effect.

Write a Button

Ant Design also provides rich, good-looking button components that use the simplest Primary button directly. The button component also needs to be introduced before using it. In order to make the component look better, we also added some Margin styles, as follows:

import React, { Component } from 'react';
import 'antd/dist/antd.css'
import { Input , Button } from 'antd'

class TodoList extends Component {
    render() { 
        return ( 
            <div style={{margin:'10px'}} >
                <div>
                    <Input placeholder='Write something' style={{ width:'250px', marginRight:'10px'}} / >
                    <Button type="primary">increase</Button>
                </div>
            </div>); }}export default TodoList;

Copy the code

The List component makes a List

We also used Ant Desgin to make the todoList list. Before making the list, we first declared a data array outside the class. The contents of the array can be written as we like.


const data=[
    'Morning meeting at 8am to assign today's development work'.'Development requirements meeting with project Manager at 9am'.'5:30 PM review of today's code'
]

Copy the code

Then import the List component as follows:

import { Input , Button , List } from 'antd'
Copy the code

The last step is to use the List component.

<div style={{margin:'10px'.width:'300px'}} ><List
        bordered
        dataSource={data}
        renderItem={item= >(<List.Item>{item}</List.Item>)} / >    
</div>
Copy the code

In order to make it easier to learn, I have given you the entire code, if you have difficulty, you can directly copy the code below.

import React, { Component } from 'react';
import 'antd/dist/antd.css'
import { Input , Button , List } from 'antd'

const data=[
    'Morning meeting at 8am to assign today's development work'.'Development requirements meeting with project Manager at 9am'.'5:30 PM review of today's code'
]

class TodoList extends Component {
    render() { 
        return ( 
            <div style={{margin:'10px'}} >
                <div>
                    <Input placeholder='write someting' style={{ width:'250px', marginRight:'10px'}} / >
                    <Button type="primary">increase</Button>
                </div>
                <div style={{margin:'10px',width:'300px'}} >
                    <List
                        bordered
                        dataSource={data}
                        renderItem={item= >(<List.Item>{item}</List.Item>)} / ></div>
            </div>); }}export default TodoList;

Copy the code

Conclusion: This class mainly uses Ant Design to make the interface of todoList, using ,

P05: Basic – Create a repository in Redux – Store and Reducer

Now that we’re officially in the coding phase of Redux, you need to focus on learning. Before you start coding, you should familiarize yourself with the redux workflow described earlier. So I also put the picture under the text for your preview. As you can see from the picture, there are four parts to the Redux workflow. The most important part is the Store, because it manages all the data in the Store. When writing code, it’s important to write store first.

Write to createstorewarehouse

To use Redux, use NPM Install to install, open the terminal, go to the project directory, and type. (If you’ve installed it before, you don’t need to install it again.)

npm install --save redux
Copy the code

After redux is installed, create a store folder in the SRC directory, and then create an index.js file under that folder.

Index.js is the store file for the entire project. Open the file and write the following code.

import { createStore } from 'redux'  // Introduce the createStore method
const store = createStore()          // Create a datastore
export default store                 // Expose
Copy the code

In this way, although the warehouse has been established, but the warehouse is very chaotic, at this time, it needs a module with management ability, which is Reducers. These two must be created together so that the repository does not play off against each other. In the Store folder, create a new file reducer.js and write the following code.

const defaultState = {}  // Default data
export default (state = defaultState,action)=>{  // is a method function
    return state
}
Copy the code
  • state: is the data information that needs to be managed in the whole project. We have no data here, so we use empty objects to represent it.

Reducer is then established. Introduce reducer into the store and pass the reducer to the store in the form of parameters when creating the store.

import { createStore } from 'redux'  // Introduce the createStore method
import reducer from './reducer'    
const store = createStore(reducer) // Create a datastore
export default store   // Expose
Copy the code

Initialize data for todoList in store

Now that the repository store and reducer have been created, we can initialize the data in todoList. Add inputValue and list to the Reducer state object. The following code

const defaultState = {
    inputValue : 'Write Something'.list: ['Wake up at 4am, exercise'.'Swim for an hour after work at noon']}export default (state = defaultState,action)=>{
    return state
}
Copy the code

It’s like you’re adding two new pieces of data to the Store.

Components forstoreThe data in the

Now that you have the store, you have the data, how do you get the data in stroe? You can introduce store first in the component you want to use. For our todoList component to use store, import it in the SRC/todolist.js folder. At this point, you can delete the previously written data.

import store from './store/index'
Copy the code

Of course you can also abbreviate it like this:

import store from './store'
Copy the code

Once you’ve introduced the Store, try printing it to the console in the constructor to see if you actually get the data, and if everything works, you can get the data.

constructor(props){
    super(props)
    console.log(store.getState())
}
Copy the code

At this point, the data cannot be used directly by the component at the UI level. We can copy the data directly to the state of the component, as shown below.

import React, { Component } from 'react';
import 'antd/dist/antd.css'
import { Input , Button , List } from 'antd'
import store from './store'



class TodoList extends Component {
constructor(props){
    super(props)
    // Key code -----------start
    this.state=store.getState();
    // Key code -----------end
    console.log(this.state)
}
    render() { 
        return ( 
            <div style={{margin:'10px'}} >
                <div>
                    
                    <Input placeholder={this.state.inputValue} style={{ width:'250px', marginRight:'10px'}} / >
                    <Button type="primary">increase</Button>
                </div>
                <div style={{margin:'10px',width:'300px'}} >
                    <List
                        bordered// Key code-----------start
                        dataSource={this.state.list}// Key code-----------end
                        renderItem={item= >(<List.Item>{item}</List.Item>)} / ></div>
            </div>); }}export default TodoList;
Copy the code

Through the above steps, we took the data out of the warehouse and used it in the component UI, which is a small step forward. In this lesson we looked at how to create a Store, reduce, and how to use data in a store. This lecture is an essential part of Redux’s thinking, and it’s important enough to go over twice.

P06: Basic -Redux Dev Tools installation

You’ve already made the state repository in Redux, and you’re ready to pull data out of the repository. Next we need to debug the data in these warehouses on the console, using Redux DevTools. Installing this requires scientific Internet access, so you need to find a good ladder first.

The installationRedux DevTools

I used Chrome to install the plugin. In the upper right corner of the browser, there are three dots, then click “More tools “, then click” Extensions “, then click “Open Chrome Web Store “, then search for Redux DevTools and you can see the plugin below.

After the installation is complete, you can see the Redux tag in the console, which also indicates that the installation was successful.

configurationRedux Dev Tools

Redux Dev Tools Redux Dev Tools Redux Dev Tools Redux Dev Tools According to the website tips, we changed the last class’s index.js code to look like the following.

import { createStore } from 'redux'  // Introduce the createStore method
import reducer from './reducer'    
const store = createStore(reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()) // Create a datastore
export default store   // Expose
Copy the code

In fact, it added this sentence.

window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
Copy the code

See if there is a method in the window, and execute it if there is (don’t be intimidated by uppercase method names).

Once this is done, you can launch the project and test it. You should see that the State data changes at a glance, and Redux debugging will be much simpler later.

So that’s it for now, and next time we’ll learn how to change State in Redux by creating an Action.

P07: Basics – Experience the flow of Redux through Input

What I want to do in this lesson is to get a feel for how Redux works by making changes to the Input. What we want to implement in the TodoList Demo is that the store value in redux changes whenever the value in the text box changes, and the component changes as the state value in Redux changes. And the whole process is this diagram that I showed you before,

Add Input response events

If you want your Input to change and redux to change with it, add the onChange response event to the Input component, open the todolist.js file in the SRC directory, and modify the code as follows:

<Input 
    placeholder={this.state.inputValue} 
    style={{ width:'250px'.marginRight:'10px'}}
    //--------- key code ----start
    onChange={this.changeInputValue}
    //--------- key code ----end
/>
Copy the code

After writing this step, remember to bind this to constructor and modify the reference to this.

constructor(props){
    super(props)
    this.state=store.getState();
    this.changeInputValue= this.changeInputValue.bind(this)}Copy the code

Once this is done, you can code the changeInputValue method. Let’s first print out the changes to the text box on the console as follows:

changeInputValue(e){
    console.log(e.target.value)
}
Copy the code

Then open your browser and press F12 to see the console results. Here is the full code so far:

import React, { Component } from 'react';
import 'antd/dist/antd.css'
import { Input , Button , List } from 'antd'
import store from './store'



class TodoList extends Component {
    constructor(props){
        super(props)
        this.state=store.getState();
        this.changeInputValue= this.changeInputValue.bind(this)}render() { 
        return ( 
            <div style={{margin:'10px'}} >
                <div>
                    <Input 
                        placeholder={this.state.inputValue} 
                        style={{ width:'250px', marginRight:'10px'}}
                        onChange={this.changeInputValue}
                    />
                    <Button type="primary">increase</Button>
                </div>
                <div style={{margin:'10px',width:'300px'}} >
                    <List
                        bordered
                        dataSource={this.state.list}
                        renderItem={item= >(<List.Item>{item}</List.Item>)} / ></div>
            </div>
         );
    }

    changeInputValue(e){
        console.log(e.target.value)
    }
}
export default TodoList;
Copy the code

The next thing we need to do is change the values in Redux, and we’ll keep going.

createAction

To change the value of State in Redux, create an Action. An Action is an object with two properties. The first is a description of the Action and the second is the value to be changed.

changeInputValue(e){
    const action ={
        type:'change_input_value'.value:e.target.value
    }
}
Copy the code

The action is created, but passed to the Store via the dispatch() method. Let’s add another line of code under action.

changeInputValue(e){
    const action ={
        type:'changeInput'.value:e.target.value
    }
    store.dispatch(action)
}

Copy the code

At this point, the Action is completely created and associated with the Store.

storeAutomatic push policy

In the previous lessons, I have said that the Store is just a repository and has no management ability. It automatically forwards the received actions to the Reducer. Now we directly print the results in Reducer for a look. Open the reducer.js file under the Store folder and modify the code.

export default (state = defaultState,action)=>{
    console.log(state,action)
    return state
}
Copy the code

At this point, two parameters can be explained:

  • State: Refers to the state in the original warehouse.
  • Action: Refers to the newly passed state of the action.

The Reducer has received the original data and the new data, and now the Reducer needs to change the values in the store. We first check if type is correct, and if so, we need to declare a new variable newState. (Remember that the Reducer only accepts states, not changes them.) So we declare a new variable and return it again.

export default (state = defaultState,action)=>{
    if(action.type === 'changeInput') {let newState = JSON.parse(JSON.stringify(state)) // Deep copy state
        newState.inputValue = action.value
        return newState
    }
    return state
}

Copy the code

Let the component update

Now that the store data has been updated, but the component has not been updated, we need to open the component file todolist.js and constructor and write the following code.

constructor(props){
    super(props)
    this.state=store.getState();
    this.changeInputValue= this.changeInputValue.bind(this)
    //---------- key code -----------start
    this.storeChange = this.storeChange.bind(this)  // Convert this to
    store.subscribe(this.storeChange) // Subscribe to Redux status
    //---------- key code -----------end
}

Copy the code

Of course we don’t have the storeChange method yet, just write the method and reset the setState once to realize that the component changes as well. At the bottom of the code, write the storeChange method.

 storeChange(){
     this.setState(store.getState())
 }
Copy the code

Now preview in the browser, and you can see that the changes have been synchronized in both the component and Redux. This lesson covers a lot of content and goes through the process of Redux. If you can write this lesson by yourself, it is considered that you have started Redux. You can watch this video twice to make sure you have a solid foundation. I’m really hard to say oh, you have to do, or you really can’t learn.

P08: Basics -Redux makes ToDoList lists

Based on the knowledge of last class, we used the same method and process to develop the list function in toDoList again. Specifically, when clicking the add button, the list of toDoList components will increase. In fact, we have knowledge, the lack of proficiency.

Write buttons to add response events and actions

To write the event that responds to the button click, open the todolist.js file and add the onClick event to the button. Remember to bind it.

<Button 
    type="primary"
    onClick={this.clickBtn} > Add </Button>Copy the code

Then bind from constructor as follows:

constructor(props){
    super(props)
    this.state=store.getState();
    this.changeInputValue= this.changeInputValue.bind(this)
    this.storeChange = this.storeChange.bind(this)
    // Key code ------------start----------
    this.clickBtn = this.clickBtn.bind(this)
    // Key code ------------end----------
    store.subscribe(this.storeChange) // Subscribe to Redux status
}
Copy the code

Once bound, you can write the clickBtn() method, which replaces the business content with a print statement.

clickBtn(){
    console.log('jspang.com')}Copy the code

At this point, preview and click the “Add button” to output jspang.com on the console. Our event was added successfully.

Create actions and usedispatch()Passed to thestore

Add the Action to the clickBtn method and pass it to the Store using the Dispatch () method as follows:

clickBtn(){
   const action = { type:'addItem'}
   store.dispatch(action)
}
Copy the code

At this time, the action has been passed to the Store, and then we can compile the business logic in Reducer.

Compile the business logic of Reducer

Open the reducer. Js file and write code to determine whether type is an addItem. If a new value is inserted into the list of Redux.

export default (state = defaultState,action)=>{
    if(action.type === 'changeInput') {let newState = JSON.parse(JSON.stringify(state)) // Deep copy state
        newState.inputValue = action.value
        return newState
    }
    // Key code ------------------start----------
    // The state value can only be passed, not used
    if(action.type === 'addItem') {// Write business logic based on type value
        let newState = JSON.parse(JSON.stringify(state)) 
        newState.list.push(newState.inputValue)  // Push the new content to the list
        newState.inputValue = ' '
        return newState
    }
     // Key code ------------------end----------
    return state
}

Copy the code

Since you wrote the subscription method last time, you can preview it in your browser at this point. You can try adding something new to it. That’s the end of the lesson. There’s nothing new to learn, but this Redux process is something you need to be familiar with, because I work with this process almost every day when I write Redux programs at work to make the interface responsive.

P09: Basic – ToDoList delete with Redux

In this section, we’ll walk through Redux again, using Redux to create the delete function. When you click on a list subitem in ToDoList, you delete the corresponding subitem. If you feel comfortable with the Redux process, stop and read the article or video, try it out yourself, and then compare.

The binding child responds to the event

Open the todolist.js file in the SRC directory and find the renderItem property of the List component. Write the following code:

<div style={{margin:'10px'.width:'300px'}} ><List
        bordered
        dataSource={this.state.list}
        renderItem={(item,index)= >(<List.Item onClick={this.deleteItem.bind(this,index)}>{item}</List.Item>)} / >    
</div>
Copy the code

And then we write this deleteItem() method, remember that it needs to take an index argument.

deleteItem(index){
    console.log(index)
}
Copy the code

So if we go to the browser and preview it, press F12 to open the console, and you can see that when you click the button you can see that the console outputs the array subscript.

Write the Redux Action in the method

Once the binding method is ready to write the action, we pass the index as follows:

deleteItem(index){
    const action = {
        type:'deleteItem',
        index
    }
    store.dispatch(action)
}
Copy the code

Reducer business logic implementation

After compiling and passing the action, go to reducer.js to compile the relevant business logic. All you need to do is delete the index of the array.

if(action.type === 'deleteItem') {let newState = JSON.parse(JSON.stringify(state)) 
    newState.list.splice(action.index,1)  // Delete the corresponding value from the array
    return newState
}
Copy the code

At this point, we have finished the basic functions of the TodoList component. Of course, this case still has many shortcomings, and we need to learn more knowledge to improve it. This lesson will stop here first, and we will continue to learn next class.

P10: Basics – Tips for writing Redux at work -1

If you’ve mastered the ToDoList Demo above, you’ve already mastered Redux, so reward yourself. But if you’re a veteran already in the workforce, you’re a little lowe when you write Redux like this, and you need to make a proper separation to make the layers clearer. In this session and the next, we’ll talk about two practical tips for Redux development.

Write Action Types singly to a file

When writing Redux Action, we write a lot of Action distributions, resulting in a lot of Action Types. If we need to name the Action by ourselves, there will be two basic problems:

  • If these Types are not managed uniformly, it is not conducive to the use of large projects, and the Settings will generate redundant codes.
  • becauseActionIn theType, be sure to andReducerIn thetypeSo there is no clear error in the browser after this part of the code or letter is written wrong, which brings great difficulty to debugging.

We will split the Action Type into a separate file. In the SRC /store folder, create a new actiontypes.js file and manage the Type set in the file.

export const  CHANGE_INPUT = 'changeInput'
export const  ADD_ITEM = 'addItem'
export const  DELETE_ITEM = 'deleteItem'
Copy the code

Import and use Action

The ationType.js file is ready to be imported into the todolist.js component with the following code:

import { CHANGE_INPUT , ADD_ITEM , DELETE_ITEM } from './store/actionTypes'
Copy the code

These constants can be used in the following code instead of the original Type values.

changeInputValue(e){
    const action ={
        type:CHANGE_INPUT,
        value:e.target.value
    }
    store.dispatch(action)
}
clickBtn(){
    const action = { type:ADD_ITEM }
    store.dispatch(action)
}
deleteItem(index){
    const action = {  type:DELETE_ITEM, index}
    store.dispatch(action)
}
Copy the code

Introduce Reducer and make changes

The actiontype. js file is also introduced, and the corresponding string is changed to a constant, the whole code is as follows:

import {CHANGE_INPUT,ADD_ITEM,DELETE_ITEM} from './actionTypes'

const defaultState = {
    inputValue : 'Write Something'.list: ['Wake up at 4am, exercise'.'Swim for an hour after work at noon']}export default (state = defaultState,action)=>{
    if(action.type === CHANGE_INPUT){
        let newState = JSON.parse(JSON.stringify(state)) // Deep copy state
        newState.inputValue = action.value
        return newState
    }
    // The state value can only be passed, not used
    if(action.type === ADD_ITEM ){ // Write business logic based on type value
        let newState = JSON.parse(JSON.stringify(state)) 
        newState.list.push(newState.inputValue)  // Push the new content to the list
        newState.inputValue = ' '
        return newState
    }
    if(action.type === DELETE_ITEM ){ // Write business logic based on type value
        let newState = JSON.parse(JSON.stringify(state)) 
        newState.list.splice(action.index,1)  // Push the new content to the list
        return newState
    }
    return state
}
Copy the code

So that completes the separation, so you might ask, what’s the point of having one more file and making the code look even more obscure? In fact, as I said at the beginning of the course, this will allow you to use, for example, add, delete, change, search, which is not going to be used once, it’s going to be used in a lot of places, so we can just use files directly, so we can avoid redundant code. Also, if we miswrite a constant name, the program will report an error directly to the browser and console, which will speed up development and reduce the time to find errors.

P11: Basics – Tips for writing Redux at work -2

This lesson continues with a look at some of the optimization techniques Redux uses at work. After learning the basics, it’s about refining your writing patterns to make your code more suitable for enterprise development needs. Keep improving, is the spirit that a craftsman should have. In fact, one of the most important spirit of programmers is the spirit of craftsmanship, constantly polishing their own code. ToDoList currently has a lot of actions in the component, and they are scattered all over the application. If it is a huge project, it will cause serious confusion. In this lesson, we will manage all the Redux actions in a single file.

writeactionCreators.jsfile

In the/SRC /store folder, create a new file called actionactiontypes.js.

import {CHANGE_INPUT}  from './actionTypes'
Copy the code

We can use const to declare a changeInputAction variable, which is an arrow function, as follows:

import {CHANGE_INPUT}  from './actionTypes'

export const changeInputAction = (value) = >({
    type:CHANGE_INPUT,
    value
})

Copy the code

Modify the code in todoList

With the files, you can introduce actionCreators.js into TodoLisit.

import {changeInputAction} from './store/actionCreatores'
Copy the code

Once introduced, the changeInputValue() method can be modified to look something like this.

changeInputValue(e){
        const action = changeInputAction(e.target.value)
        store.dispatch(action)
    }
Copy the code

It’s perfectly normal to open the application in your browser and test it.

Modify the other two Action methods

To install the above example and modify the other two methods, the actioncreators.js code is as follows:

import {CHANGE_INPUT , ADD_ITEM,DELETE_ITEM}  from './actionTypes'

export const changeInputAction = (value) = >({
    type:CHANGE_INPUT,
    value
})

export const addItemAction = () = >({
    type:ADD_ITEM
})

export const deleteItemAction = (index) = >({
    type:DELETE_ITEM,
    index
})


Copy the code

Once this file is written, you can change all the actions in the todolist.js file to call methods directly. The code is as follows:

import React, { Component } from 'react';
import 'antd/dist/antd.css'
import { Input , Button , List } from 'antd'
import store from './store'
// Key code -------------start
import {changeInputAction , addItemAction ,deleteItemAction} from './store/actionCreatores'
// Key code ------------end

class TodoList extends Component {
constructor(props){
    super(props)
    this.state=store.getState();
    this.changeInputValue= this.changeInputValue.bind(this)
    this.storeChange = this.storeChange.bind(this)
    this.clickBtn = this.clickBtn.bind(this)
    store.subscribe(this.storeChange) // Subscribe to Redux status
}
    render() { 
        return ( 
            <div style={{margin:'10px'}} >
                <div>
                    <Input 
                        placeholder={this.state.inputValue} 
                        style={{ width:'250px', marginRight:'10px'}}
                        onChange={this.changeInputValue}
                        value={this.state.inputValue}
                    />
                    <Button 
                        type="primary"
                        onClick={this.clickBtn}
                    >increase</Button>
                </div>
                <div style={{margin:'10px',width:'300px'}} >
                    <List
                        bordered
                        dataSource={this.state.list}
                        renderItem={(item,index)= >(<List.Item onClick={this.deleteItem.bind(this,index)}>{item}</List.Item>)} / ></div>
            </div>
         );
    }
    storeChange(){
        console.log('store changed')
        this.setState(store.getState())
    }
    //-------- key code ------start
    changeInputValue(e){
        const action = changeInputAction(e.target.value)
        store.dispatch(action)
    }
    clickBtn(){
        const action = addItemAction()
        store.dispatch(action)
    }
    deleteItem(index){
        const action = deleteItemAction(index)
        store.dispatch(action)
    }
    //-------- key code ------end
}
export default TodoList;
Copy the code

All written, we can go to the browser to view, the function is also completely ok. In this lesson we will implement the separation of Redux Action and business logic, which I think is absolutely necessary in your actual work. This improves the maintainability of the provider.

P12: Extra meals -Redux fill three small holes

This is the end of the basics of Redux, but IT’s worth taking another lesson to summarize some of the mistakes you’re prone to make. You probably already know everything in this lecture, so you can skip it. I’ve rounded up three common mistakes that newcomers to React make.

  • storeMust be unique, multiplestoreIs absolutely not allowed, only onestorespace
  • onlystoreCan change their own content,ReducerCan’t change
  • ReducerIt has to be a pure function

StoreIt has to be unique

If you look at the todolist.js code, you can see that there is a file called /store/index.js, and in this file only the createStore() method is used to declare a store, which is then used throughout the application. Here I present the contents of index.js to help you review them better.

import { createStore } from 'redux'  // Introduce the createStore method
import reducer from './reducer'    
const store = createStore(
    reducer,
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()) // Create a datastore
export default store   // Expose
Copy the code

onlystoreCan change their own content,ReducerCan’t change

Many novice partners will think that the business logic is written in the Reducer, so the state value must be changed by the Reducer. In fact, it is not. In the Reducer, we only made a return, which was returned to the store without any changes. And I’m going to focus on this in the lecture. Let’s review the Reducer code again to deepen the impression.

Reudcer only returned the changed data, but did not change the data in the store. The store got the data from the Reducer and updated itself.


import {CHANGE_INPUT,ADD_ITEM,DELETE_ITEM} from './actionTypes'

const defaultState = {
    inputValue : 'Write Something'.list: ['Wake up at 4am, exercise'.'Swim for an hour after work at noon']}export default (state = defaultState,action)=>{
    if(action.type === CHANGE_INPUT){
        let newState = JSON.parse(JSON.stringify(state)) // Deep copy state
        newState.inputValue = action.value
        return newState
    }
    // The state value can only be passed, not used
    if(action.type === ADD_ITEM ){ // Write business logic based on type value
        let newState = JSON.parse(JSON.stringify(state)) 
        newState.list.push(newState.inputValue)  // Push the new content to the list
        newState.inputValue = ' '
        return newState
    }
    if(action.type === DELETE_ITEM ){ // Write business logic based on type value
        let newState = JSON.parse(JSON.stringify(state)) 
        newState.list.splice(action.index,1)  // Push the new content to the list
        return newState
    }
    return state
}
Copy the code

ReducerIt has to be a pure function

Let’s look at what a pure function is.

If the function is called with the same arguments, the same result is always returned. It does not depend on any changes in state or data outside the function during program execution and must depend only on its input parameters.

This is supposed to be college stuff, but you might have forgotten it, but you can simply say that the result returned is determined by the value passed in, not by anything else. Take the Reducer code below.

export default (state = defaultState,action)=>{
    if(action.type === CHANGE_INPUT){
        let newState = JSON.parse(JSON.stringify(state)) // Deep copy state
        newState.inputValue = action.value
        return newState
    }
    // The state value can only be passed, not used
    if(action.type === ADD_ITEM ){ // Write business logic based on type value
        let newState = JSON.parse(JSON.stringify(state)) 
        newState.list.push(newState.inputValue)  // Push the new content to the list
        newState.inputValue = ' '
        return newState
    }
    if(action.type === DELETE_ITEM ){ // Write business logic based on type value
        let newState = JSON.parse(JSON.stringify(state)) 
        newState.list.splice(action.index,1)  // Push the new content to the list
        return newState
    }
    return state
}
Copy the code

Its return is entirely determined by the parameters state and action passed in, which is a pure function. How does this go wrong in practice? For example, adding an asynchronous Ajax function in the Reducer to get some back-end interface data and then return is not allowed (including using date functions), because it violates the pure function rule that calls with the same parameters return the same.

Next, I will continue to explain the advanced part of Redux to you, so that you can be more proficient and in-depth in using Redux. I am Technical Fat, a blogger who makes free front-end videos. Let’s cheer together.

P13: Advanced – component UI and business logic split method

You’ve learned the basics of Redux, but you’re one step away from being a master, which is how to split the UI from the business logic to make your project easier to maintain. You may ask if there are other benefits besides easier maintenance, and there are. Can split, on behalf of more people can cooperate, to achieve the development of super-large projects and quickly online. For example, two people write a module at the same time, one for the UI part, one for the business logic part, and then two people integrate together. In small companies, you may not see this as an obvious advantage because the company’s financial resources or lack of developers limit this approach. But big companies, they don’t need money, they don’t need people, they just need time, and then this development model can solve the problem. This is why I strongly recommend you to go to a big company. Although the technology is the same, the development model of big company and small company is completely different. Getting back to the point, let’s see how to separate the UI and business logic of a component.

Breaking up UI components

As you can see that the todolist.js component is fully coupled to the UI and business logic, create a new file called todolistui.js in the SRC directory to quickly generate the basic structure of the page.

import React, { Component } from 'react';
class TodoListUi extends Component {
    
    render() { 
        return ( <div>123</div>); }}export default TodoListUi;
Copy the code

Then go to todolist.js and copy the JSX part, now the code is as follows (of course, it is not available now, many things we have not introduced, so it will error):

import React, { Component } from 'react';
class TodoListUi extends Component {
    
    render() { 
        return ( 
            <div style={{margin:'10px'}} >
                <div>
                    <Input 
                        placeholder={this.state.inputValue} 
                        style={{ width:'250px', marginRight:'10px'}}
                        onChange={this.changeInputValue}
                        value={this.state.inputValue}
                    />
                    <Button 
                        type="primary"
                        onClick={this.clickBtn}
                    >increase</Button>
                </div>
                <div style={{margin:'10px',width:'300px'}} >
                    <List
                        bordered
                        dataSource={this.state.list}
                        renderItem={(item,index)= >(<List.Item onClick={this.deleteItem.bind(this,index)}>{item}</List.Item>)} / ></div>
            </div>); }}export default TodoListUi;

Copy the code

In order to use antD, the first step is to import the antD class library. At this time, you can copy the relevant code of Todolist.js, and copy the ANTD CSS and the components used.

import 'antd/dist/antd.css'
import { Input , Button , List } from 'antd'
Copy the code

However, this does not have the state information required by the todolistui.js component, so you need to modify the parent component to pass the value.

TodoList.jsFile modification

You don’t need so much JSX code in Todolist.js, just introduce Todolistui.js.

import TodoListUI from './TodoListUI'
Copy the code

The render function can be written as follows.

render() { 
    return ( 
        <TodoListUI />
    );
}
Copy the code

This completes the first step in separating the UI from the business. All that remains is to change the properties of todolistui.js, which is the integration of the two components.

Integration of UI components and business logic components

In fact, integration is through the form of attribute value, the required value is passed to the child components, the child components receive these values, the corresponding binding can be. This step is a bit more, or watch the video to learn.

The render part of todolist.js

render() { 
    return ( 
        <TodoListUI 
            inputValue={this.state.inputValue}
            list={this.state.list}
            changeInputValue={this.changeInputValue}
            clickBtn={this.clickBtn}
            deleteItem={this.deleteItem}
        />
    );
}
Copy the code

You also need to rebind this to the deleteItem method in the constructor function as follows.

this.deleteItem = this.deleteItem.bind(this)
Copy the code

After modifying the todolist.js file, the UI component should be replaced with the corresponding attributes. All the codes are as follows.

import React, { Component } from 'react';
import 'antd/dist/antd.css'
import { Input , Button , List } from 'antd'
class TodoListUi extends Component {
    
    render() { 
        return ( 
            <div style={{margin:'10px'}} >
                <div>
                    <Input  
                        style={{ width:'250px', marginRight:'10px'}}
                        onChange={this.props.changeInputValue}
                        value={this.props.inputValue}
                    />
                    <Button 
                        type="primary"
                        onClick={this.props.clickBtn}
                    >increase</Button>
                </div>
                <div style={{margin:'10px',width:'300px'}} >
                    <List
                        bordered
                        dataSource={this.props.list}
                        renderItem={(item,index)= >(<List.Item onClick={(index)= >{this.props.deleteItem(index)}}>{item}</List.Item>)} / ></div>
            </div>); }}export default TodoListUi;
Copy the code

Note that the delete function in the List component needs to replace the previous method with the arrow function, and use the attribute method in the arrow function to call the method you come from.

<List
    bordered
    dataSource={this.props.list}
    renderItem={(item,index) = >(<List.Item onClick={(index)= >{this.props.deleteItem(index)}}>{item}</List.Item>)} / >Copy the code

Once you’ve done that, you’ve split the components. The purpose of this lesson is not the steps, but the idea of splitting. You can do this a few times to deepen your understanding of the UI and business logic splitting. Front-end free course is looking for technology fat, see you next class.

P14: Advanced – stateless components in pit filling and Redux

When I finished writing the program in last class, THERE was a small mistake, which I didn’t notice at that time. It was my friend in the VIP group who told me about it. I inadvertently left a hole for everyone and said SORRY to everyone. In this lesson we’ll address this legacy and talk about stateless components. A stateless component is simply a function that no longer inherits any classes and, as the name suggests, has no state. Because the stateless component is really just a function (method), it also performs better than the regular React component.

Fat brother turned over the car to fill the hole

After writing UI and business separation in last class, there was a mistake when deleting TodoList’s project, which was a business logic error, not a syntax error. When deleting an item, there is no problem with sequential deletion, but there is a problem with reverse deletion. The main problem is the redeclaration of our index.

The original error code looks like this:

<List
    bordered
    dataSource={this.props.list}
    renderItem={(item,index) = >(<List.Item onClick={(index)= >{this.props.deleteItem(index)}}>{item}</List.Item>)} / >Copy the code

Just change it to the following and it works.

 <List
    bordered
    dataSource={this.props.list}
    renderItem={
        (item,index) = >(
            <List.Item onClick={()= >{this.props.deleteItem(index)}}>
                {item}
            </List.Item>
        )
    }
/>    
Copy the code

Rewriting of stateless components

Changing the UI component to stateless can improve performance. See how to write it.

  1. First we don’t need to introduce React{ Component }Just delete it.
  2. And then one moreTodoListUIFunction, which only returnsJSXI can copy this step.
  3. The function passes apropsParameters, and then modify all of thempropsTo remove thethis.

Here is the stateless component code that was modified to be more efficient than the normal React component.

import React from 'react';
import 'antd/dist/antd.css'
import { Input , Button , List } from 'antd'

const TodoListUi = (props) = >{
    return(
        <div style={{margin:'10px'}} >
            <div>
                <Input  
                    style={{ width:'250px', marginRight:'10px'}}
                    onChange={props.changeInputValue}
                    value={props.inputValue}
                />
                <Button 
                    type="primary"
                    onClick={props.clickBtn}
                >increase</Button>
            </div>
            <div style={{margin:'10px',width:'300px'}} >
                <List
                    bordered
                    dataSource={props.list}
                    renderItem={
                        (item.index) = >(
                            <List.Item onClick={()= >{props.deleteItem(index)}}>
                                {item}
                            </List.Item>
                        )
                    }
                />    
            </div>
        </div>)}export default TodoListUi;
Copy the code

In this lesson, we learned about stateless components in React. In the past, it was difficult to separate components without Redux. However, now we are working on projects, we must think about finding a component that can be stateless. If you can make it stateless, try to make it stateless, because performance is much higher.

P15: Advanced -Axios asynchronously retrieves data and combines it with Redux

In recent days, my friends have asked me a lot of questions, that is, how to get data from the back-end interface and put it into the Store of Redux. Many friends are stuck by this difficulty. In this lesson, learn how to get data from the background and combine it with Redux to implement the desired business logic. For example, our list data was written dead in Reducer before, this lesson uses Axios to obtain data from the background.

Create mock data using easy-mock

We’ve already covered this in the foundation course, so I’m not going to go over it too much, but if you don’t know how to do it, you can just go over the foundation course, and it’s not fun to go over it. If you say I don’t want to build a new one either, you can use my simulation data, and I’ll give you the address here.

Address: www.easy-mock.com/mock/5cfcce…

If the above interface doesn’t work, you can use Easy Mock to create your own:

{
  "data": {
    "list"[' Morning4Wake up at midnight, exercise ', 'swim for an hour after work at noon ',' in the evening8Point to the10Point, study two hours']}}Copy the code

Installation and useAxios

Because we used new projects and directories in our Redux study, we need to reinstall the Axios plug-in (previously installed ones are no longer usable). Install directly using NPM.

npm install --save axios
Copy the code

Once installed, it’s ready to be introduced and used in Todolist.js.

import axios from 'axios'
Copy the code

Once introduced, componentDidMount retrieves remote interface data in the component’s declaration cycle function.

componentDidMount(){
    axios.get('https://www.easy-mock.com/mock/5cfcce489dc7c36bd6da2c99/xiaojiejie/getList').then((res) = >{
        console.log(res)
    })
}
Copy the code

After this step, you can open it in the browser and preview whether the console can get the data. If so, it is completely normal.

After data acquisitionReduxCombine (emphasis)

And then we can put that data into the Redux store, and this is the same as we’ve seen before, so I’m going to try to give you the code, not the theory. Create a function, open the store/ actioncreators. js function you wrote earlier, and write a new function as follows:

export const getListAction  = (data) = >({
    type:GET_LIST,
    data
})

Copy the code

The GET_LIST is not found when saved, so we add a constant to actiontypes.js and import it to actioncreators.js

export const  GET_LIST = 'getList'
Copy the code

Into actioncreators.js

import {CHANGE_INPUT , ADD_ITEM , DELETE_ITEM , GET_LIST}  from './actionTypes'
Copy the code

Once you’ve done that, go back to the todolist.js file and continue writing the callback content in AXIos, including getListAction before writing.

import {changeInputAction , addItemAction ,deleteItemAction,getListAction} from './store/actionCreatores'
Copy the code
componentDidMount(){
    axios.get('https://www.easy-mock.com/mock/5cfcce489dc7c36bd6da2c99/xiaojiejie/getList').then((res) = >{    
        const data = res.data
        const action = getListAction(data)
        store.dispatch(action)
    })
}
Copy the code

Now that the data has been sent to the store via Dispatch, the reducer needs to handle the business logic. Open reducer.js as follows (detailed steps are commented in the code) :

//---- key code --------start -------- introduces GET_LIST
import {CHANGE_INPUT,ADD_ITEM,DELETE_ITEM,GET_LIST} from './actionTypes'
//---- key code --------end
const defaultState = {
    inputValue : 'Write Something'.//---- key code --------start -------- Deletes the original initialization code to reduce redundancy
    list:[]
}
export default (state = defaultState,action)=>{
    if(action.type === CHANGE_INPUT){
        let newState = JSON.parse(JSON.stringify(state)) // Deep copy state
        newState.inputValue = action.value
        return newState
    }
    if(action.type === ADD_ITEM ){ 
        let newState = JSON.parse(JSON.stringify(state)) 
        newState.list.push(newState.inputValue)  // Push the new content to the list
        newState.inputValue = ' '
        return newState
    }
    if(action.type === DELETE_ITEM ){ // Write business logic based on type value
        let newState = JSON.parse(JSON.stringify(state)) 
        newState.list.splice(action.index,1)  // Push the new content to the list
        return newState
    }
    //---- key code --------start --------
    if(action.type === GET_LIST ){ // Write business logic based on type value
        let newState = JSON.parse(JSON.stringify(state)) 
        newState.list = action.data.data.list // Copy the List array
        return newState
    }
    //---- --------en'd --------

    return state
}
Copy the code

This completes the process of requesting data from the background and then combining it with Redux. Hope friends can practice, our programmers more and more like real development, partners should also be constantly familiar with this development mode in the exercise.

P16: Installation and configuration of advanced – Redux-Thunk middleware

You have a thorough understanding of the basic process of Redux, and you may have started using it in your projects. We’ve actually covered most of Redux together, but I decided to continue with redux-Thunk, the most commonly used plug-in for Redux. When will this plugin be used? For example, after dispatching an Action and before arriving at the reducer, additional operations need to be done using middleware. In practice you can use middleware to log, create crash reports, invoke asynchronous interfaces, or route. This middleware can be enhanced with redux-Thunk (of course you can use other middleware), which is an enhancement to Redux dispatch. In this lesson we will learn about the installation and configuration of redux-Thunk.

The installationRedux-thunkcomponent

Redux-thunk is not part of the Redux base component, which means a new installation is required. Install using NPM.

npm install --save redux-thunk
Copy the code

Enter the command above in the terminal command line, you can install, according to the different network installation time will be somewhat different, my office network is second press, home broadband needs about 10 minutes.

configurationRedux-thunkcomponent

Installation is easy, but configuration requires a little care, there are still a few holes, if you follow the official documentation will not be successful configuration. Redux-thunk needs to be introduced where the store is created, which for our directory is the /store/index.js file.

1. Introduce applyMiddleware. If you want to use middleware, you must include applyMiddleware in Redux.

import { createStore , applyMiddleware } from 'redux' 
Copy the code

2. Import the redux-Thunk library

import thunk from 'redux-thunk'
Copy the code

If you follow the documentation, you can simply put thunk as the second parameter in createStore, but we configured Redux Dev Tools to use the second parameter.

The official document gives the method:

const store = createStore(
    reducer,
    applyMiddleware(thunk)
) // Create a datastore
Copy the code

This is perfectly fine, but our Redux Dev Tools plugin won’t work, and if you want to use both, you’ll need to use the enhancement function. You need to introduce compose before using the increment function.

import { createStore , applyMiddleware ,compose } from 'redux' 
Copy the code

Compose then creates an enhancement function for compose, which is equivalent to creating a chain function as follows:

const composeEnhancers =   window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}):compose
Copy the code

With the enhancement function, you can add thunk so that both functions will execute.

const enhancer = composeEnhancers(applyMiddleware(thunk))
Copy the code

This is done by using the enhancer variable as the second parameter in the createStore function.

const store = createStore( reducer, enhancer) // Create a datastore
Copy the code

Maybe you don’t fully understand the increment function, but actually you think of this as fixed code, so you can use it directly, and I’m going to give you the whole code here, so you can learn to use it later.

import { createStore , applyMiddleware ,compose } from 'redux'  // Introduce the createStore method
import reducer from './reducer'    
import thunk from 'redux-thunk'

const composeEnhancers =   window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}):compose

const enhancer = composeEnhancers(applyMiddleware(thunk))

const store = createStore( reducer, enhancer) // Create a datastore
export default store   // Expose
Copy the code

Now that you have Redux’s middleware configured, you can run the project, see the results in the browser, and take a look at the Redux Dev Tools plug-in.

P17: Use of advanced – redux-thunk

This lesson we put request data to the background programs in the middleware, thus formed a complete set of Redux process, all the logic is done in the interior of the story, it looks more perfect, and do simple test automation will change a lot, so the work you still want to try to write in this way. Start learning now.

inactionCreators.jsTo write the business logic

Actionactionine.js used to be defined actions, so you couldn’t write the business logic. With Redux-Thunk, you can write the componentDidMount business logic in Todolist.js. That is, the code that requests data from the background is put in the actionActioncreans.js file. So we need to introduce Axios and write a new function method. (Once actions were objects, now actions can be functions. That’s what redux-thunk brings.)

import axios from 'axios'. something...export const getTodoList = () = >{
    return () = >{
        axios.get('https://www.easy-mock.com/mock/5cfcce489dc7c36bd6da2c99/xiaojiejie/getList').then((res) = >{
            const data = res.data
            console.log(data)
        })
    }
}
Copy the code

Now we need to execute the method and view the results on the console, where we can modify the componentDidMount code in the todolist.js file.

// Start with getTodoList
import {getTodoList , changeInputAction , addItemAction ,deleteItemAction,getListAction} from './store/actionCreatores'
---something---
componentDidMount(){
    const action = getTodoList()
    store.dispatch(action)
}

Copy the code

Then we go to the browser console and check to see if we’ve got the data that was sent to us from the back end. If everything works, we should. Once we get that, we can just continue with the old Redux process.

export const getTodoList = () = >{
    return (dispatch) = >{
        axios.get('https://www.easy-mock.com/mock/5cfcce489dc7c36bd6da2c99/xiaojiejie/getList').then((res) = >{
            const data = res.data
            const action = getListAction(data)
            dispatch(action)
            
        })
    }
}
Copy the code

This function can pass in the dispatch directly, which is automatic, and then we can pass in the dispatch(action) directly. Now we can open the browser and test.

At this time, there will be some warnings, mainly because we introduced but did not use, we follow the warning prompt, delete useless introduction is ok.

You may find this convoluted, as I did when I first started Redux, but as the project gets bigger, you’ll find that it makes perfect sense to incorporate the business logic of shared state into your Redux prompts, which will make your program more organized. In automated testing, a method can be tested directly, while life cycle testing is difficult. All the big companies I have contacted require writing in this way. If you still can’t understand the benefits, don’t worry about it. Write in this form first. After you’ve written two or three projects, you’ll understand the benefits of this approach.

P18: Advanced – Redux-Saga installation and configuration

First of all, the middleware we are talking about here is not the React middleware, but the Redux middleware. You need to understand this, otherwise there will be big problems in your work, and your React knowledge architecture will also be biased. In fact, Redux middleware is not only Redux-Thunk, there is also a relatively famous redux-Saga. Of course, our company has not used this middleware, but only studied it by ourselves, so we may explain the shortcomings. At present, domestic IT enterprises are generally using these two middleware, with few others, just like Coca Cola and Pepsi Cola, so IT is necessary to learn.

The installation of story – saga

You can use NPM directly to install, of course, yarn is also no problem, according to your preferences. I used NPM here for the installation.

npm install --save redux-saga
Copy the code

Github address is given here to facilitate your better study.

Github.com/redux-saga/…

Import and createRedux-saga

/ SRC /store/index.js to import Redux-saga and create a sagaMiddleware:

import createSagaMiddleware from 'redux-saga'   / / into the saga
const sagaMiddleware = createSagaMiddleware();   // Create saga middleware

Copy the code

Once created, Redux’s enhancements are passed in. Redux-thunk was replaced with saga middleware (note the removal of the redux-Thunk introduction).

import { createStore , applyMiddleware ,compose } from 'redux'  // Introduce the createStore method
import reducer from './reducer'   
//------ key code ----start-----------
import createSagaMiddleware from 'redux-saga' 
const sagaMiddleware = createSagaMiddleware();
//------ key code ----end-----------

const composeEnhancers =   window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}):compose
//------ key code ----start-----------
const enhancer = composeEnhancers(applyMiddleware(sagaMiddleware))
//------ key code ----end-----------

const store = createStore( reducer, enhancer) // Create a datastore
export default store   // Expose

Copy the code

Once this is done, redux-thunk is replaced with redux-saga, which is not available yet, as we need to continue to configure the sagas.js file.

createsagas.jsFile and import

Redux-saga wants you to write your business logic in a separate file. Here we create a sagas.js file in the/SRC /store/ folder.

function* mySaga() {} 
export default mySaga;

Copy the code

Once created, it’s imported directly into index.js.

import mySagas from './sagas' 
Copy the code

Then execute the run method to get Saga running.

sagaMiddleware.run(mySagas)
Copy the code

For your convenience, here is the full contents of/SRC /store/index.js.

import { createStore , applyMiddleware ,compose } from 'redux'  // Introduce the createStore method
import reducer from './reducer'   
import createSagaMiddleware from 'redux-saga' 
import mySagas from './sagas' 

const sagaMiddleware = createSagaMiddleware();

const composeEnhancers =   window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}):compose
const enhancer = composeEnhancers(applyMiddleware(sagaMiddleware))
const store = createStore( reducer, enhancer) 
sagaMiddleware.run(mySagas)


export default store  

Copy the code

Now it has been completely replaced with redux-saga, so the previous code in todolist.js needs to be deleted, otherwise an error will be reported. The main thing to remove is the code in the componentDidMount declaration periodic function. With redux-Saga installed and configured, we can write middleware. In fact, this configuration usually only needs to be done once in the project, you can bookmark the page, and then come back to look at it when you need.

P19: Advanced – Get the TodoList list with Redux-Saga

This article will use Redux-Saga to get the list of TodoList. Redxu-saga is actually more complex than Redux-Thunk, with more apis to learn, or at least more cost. However, some people say that Saga is more suitable for large projects. I don’t want to take a position and I don’t want to start a war. If your company uses Saga, these two articles will get you started. Without further ado, let’s continue our study.

writeTodoList.jsfile

Todolist.js is now componentDidMount is empty, so we’re going to do some basic redux. I’m not going to talk about this anymore, but I’ve done it a dozen times.

You can introduce an action, which you don’t have yet, but we’ll write it later, and call it getMyListAction. (You can call it anything, just remember, because we’re going to be using it all the time.)

import {getMyListAction, changeInputAction , addItemAction ,deleteItemAction} from './store/actionCreatores'
Copy the code

Then create the action in the actionactionine.js file.

export const getMyListAction = () = >({
    type:GET_MY_LIST
})

Copy the code

You’ll notice that GET_MY_LIST doesn’t have one either, so you’ll need to import it first and then define it in actiontypes.js

import {GET_MY_LIST,CHANGE_INPUT , ADD_ITEM,DELETE_ITEM,GET_LIST}  from './actionTypes'
Copy the code

The actiontypes.js file defines GET_MY_LIST

export const  GET_MY_LIST = 'getMyList'
Copy the code

Then you can go back to the todolist.js file and write the stuff in componentDidMount.

componentDidMount(){
    const action =getMyListAction()
    store.dispatch(action)
    console.log(action)
}
Copy the code

Once the test is complete, you can delete console.log(), keeping the code clean and without redundancy.

Writing sagas.js files (also business logic)

The middleware business logic for saga is written in this sagas.js file, where we use mySaga as the entry function. Capture the action type passed in the entry function and call different methods depending on the type.

import { takeEvery } from 'redux-saga/effects'  
import {GET_MY_LIST} from './actionTypes'

/ / function generator
function* mySaga() {
    // Wait for the capture action
    yield takeEvery(GET_MY_LIST, getList)
}

function* getList(){
    console.log('jspang')}export default mySaga;
Copy the code

After writing the above code, let’s see if we can print the result correctly in the browser console. If we can print the result successfully, we have made it correctly so far. And then we’re going to use Axios to request the result.

Sagas.js is covered here and explained in detail in the video.

import { takeEvery ,put } from 'redux-saga/effects'  
import {GET_MY_LIST} from './actionTypes'
import {getListAction} from './actionCreatores'
import axios from 'axios'

/ / function generator
function* mySaga() {
    // Wait for the capture action
    yield takeEvery(GET_MY_LIST, getList)
}

function* getList(){
    // I will not delete this code.
    // axios.get('https://www.easy-mock.com/mock/5cfcce489dc7c36bd6da2c99/xiaojiejie/getList').then((res)=>{
    // const data = res.data
    // const action = getListAction(data)
    // put(action)
        
    // })
    const res = yield axios.get('https://www.easy-mock.com/mock/5cfcce489dc7c36bd6da2c99/xiaojiejie/getList')
    const action = getListAction(res.data)
    yield put(action)
}
  
export default mySaga;
Copy the code

Summary: This is the basic way to use Redux-Saga. There are a few other saga apis, but I don’t use them very much at work, so this is just to make sure you are getting started. There is no debate here as to whether redux-thunk or Redux-saga is a good question. As the popular Internet saying goes, multiple-choice questions are for kids and technology veterans learn them all.

P20: Introduction and installation of advanced React-redux

React-redux is a common component in the React ecosystem. It can simplify the Redux process. In this lesson, we will re-create a project called Demo02 and use react-Redux to re-implement the TodoList case in several classes. If your company doesn’t use this plugin, there’s no need to spend time learning it. But as an essay, you must make sure that the knowledge is as complete as possible. (Note the concept: React, Redux, and React-Redux are three different things.)

ReactProject initialization

Since the scaffolding tool creat-react-app was previously installed, type the following command directly into the project terminal.

create-react-app demo02
cd demo02
npm start
Copy the code

After the above three commands, the following interface should appear in the browser (the screen shows that our project initialization is complete).

After the installation is complete, it is normal to remove unnecessary styles and code, save one index.js file in/SRC, and delete the rest.

import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(<App />.document.getElementById('root'));
Copy the code

The installationreact-redux

After the project is initialized, install React-Redux directly from the command line using NPM. The installation time for this network varies depending on the network.

npm install --save react-redux
Copy the code

The installed version of video recording is 7.1.0, you may be different from me when learning, if there is a difference, you can check the latest API documentation on Github.

Modify the code to make him run

Currently the project is not running, so we need to create a todolist.js component. The project code is as follows:

import React, { Component } from 'react';
class TodoList extends Component {
    render() { 
        return ( <div>JSPang</div>); }}export default TodoList;
Copy the code

Now that we have todolist.js, we import it into the index.js file and modify the code as follows:

import React from 'react';
import ReactDOM from 'react-dom';
import TodoList from './TodoList'
ReactDOM.render(<TodoList />.document.getElementById('root'));
Copy the code

When you preview it in a browser, you’ll just output the word JSPang. It’s ugly, but the project is running. Let’s write the JSX page in the Render function (we won’t use ANTD to save you time).

render() { 
    return (
        <div>
            <div><input /><button>submit</button></div>
            <ul>
                <li>JSPang</li>
            </ul>
        </div>
        );
}
Copy the code

At this point the interface should have changed a little bit, so that we can complete the initialization of the basic project, and then we can make a store as the original Redux.

ReduxInstallation and Use of (review)

Install the Redux package in the terminal first, because it is a new project and needs to be reinstalled.

npm install --save redux
Copy the code

First create a store folder, create an index.js file under /store, and write the following code:

import {createStore} from 'redux'
import reducer from './reducer'

const store = createStore(reducer)

export default store
Copy the code

At present we do not have reducer, so we need to create reducer. Js as follows:

const defalutState = {
    inputValue : 'jspang'.list :[]
}

export default (state = defalutState,action) =>{
    return state
}
Copy the code

It is then used in the constructor of todolist.js.

import React, { Component } from 'react';
//----- key code --------start
import store from './store'
//----- key code --------end
class TodoList extends Component {
    //----- key code --------start
    constructor(props){
        super(props)
        this.state = store.getState()
    }
    //----- key code --------end
    render() { 
        return (
            <div>
                <div>//----- key code --------start<input value={this.state.inputValue} />//----- key code --------end<button>submit</button>
                </div>
                <ul>
                    <li>JSPang</li>
                </ul>
            </div>); }}export default TodoList;

Copy the code

So far, we’ve only installed react-redux, but we haven’t used it yet. In this lesson, we just need to set up the basic environment and review the previous knowledge. React-redux: React-Redux: React-Redux: React-Redux: React-Redux

P21: Provider and connect in advanced react-redux

Last time, we completed the basic environment for developing TodoList components with React-Redux. Now you can learn about React-Redux. In this lesson, we will learn about Provider and connect.

<Provider>Provider explanation

is a Provider. Once you use this component, all other components in the component can use store, which is the core component of React-Redux. With , you can rewrite/SRC /index.js into the following code style, explained in the video.

import React from 'react';
import ReactDOM from 'react-dom';
import TodoList from './TodoList'
//--------- key code --------start
import { Provider } from 'react-redux'
import store from './store'
// Declare an App component that is wrapped with a Provider.
const App = (
   <Provider store={store}>
       <TodoList />
   </Provider>
)
//--------- key code --------end
ReactDOM.render(App, document.getElementById('root'));
Copy the code

After writing this, we went back to the browser and saw that the code worked perfectly. It is important to note that the data in the Store is still retrieved the traditional way. Getting data with a Provider is much less of a hassle.

connectUse of connectors

Now how do I get the data in the store easily? Open the todolist.js file and introduce Connect, which is a connector (actually a method) that makes it easy to retrieve data.

import {connect} from 'react-redux'  // Import the connector
Copy the code

This exposes connect, and the code is as follows.

export default connect(xxx,null)(TodoList);
Copy the code

Here XXX represents a mapping relationship, which has not been made yet.

Mapping relationship making

The mapping is to map the original state to the props property in the component. For example, if we want to map inputValue, we can write the following code.

const stateToProps = (state) = >{
    return {
        inputValue : state.inputValue
    }
}
Copy the code

Now change XXX to stateToProps

export default connect(stateToProps,null)(TodoList)
Copy the code

Then change the state tag in to props as follows:

 <input value={this.props.inputValue} />
Copy the code

For your convenience, I’m giving you all the code for todolist.js.

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

class TodoList extends Component {
    constructor(props){
        super(props)
        this.state = store.getState()
    }
    render() { 
        return (
            <div>
                <div>
                    <input value={this.props.inputValue} />
                    <button>submit</button>
                </div>
                <ul>
                    <li>JSPang</li>
                </ul>
            </div>); }}const stateToProps = (state) = >{
    return {
        inputValue : state.inputValue
    }
}
 
export default connect(stateToProps,null)(TodoList);
Copy the code

After writing it, check it in the browser and see that our mapping also works. This lesson is about using the React-Redux plugin. You’ll need to write it a few times to keep the process in mind. That’s it. Next time we’ll continue implementing the TodoList component.

P22: Advanced react-redux data modification

React-redux was used to get Store data successfully in last class. This lesson is about changing data in a Store. That is, when we change the value in to change the store data, the UI changes accordingly.

writeonChangeRespond to events

Open the todolist. js file and register the onChange event in

 <input value={this.props.inputValue} onChange={this.inputChange.bind(this)} / >Copy the code

With an event to write corresponding methods, here is the simplest inputChange method.

inputChange(e){
    console.log(e.target.value)
}
Copy the code

Then when you go to the console in the browser, there are no more errors, and you can print out the value when you type, which means our binding is successful. So now that we’re done we’re going to change to react-redux.

writeDispatchToProps

To use react-redux, we can write another mapping of DispatchToProps. If you look at this code, you can see that there are two arguments. The second argument is null.

export default connect(stateToProps,null)(TodoList);
Copy the code

DispatchToProps is the second parameter to pass in order to change the value in store.

const dispatchToProps = (dispatch) = >{
    return {
        inputChange(e){
            console.log(e.target.value)
        }
    }
}
Copy the code

With this parameter you can change the response event to the following code.

 <input value={this.props.inputValue} onChange={this.props.inputChange} />
Copy the code

Then pass the connect second parameter.

export default connect(stateToProps,dispatchToProps)(TodoList);
Copy the code

In this case, the original inputChange method is useless and can be deleted. Now the overall code looks like this, and we can see it in a preview in the browser. If this step succeeds, the mapping relationship is supported successfully.

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

class TodoList extends Component {
    constructor(props){
        super(props)
        this.state = store.getState()
    }
    render() { 
        return (
            <div>
                <div>
                    <input value={this.props.inputValue} onChange={this.props.inputChange} />
                    <button>submit</button>
                </div>
                <ul>
                    <li>JSPang</li>
                </ul>
            </div>); }}const stateToProps = (state) = >{
    return {
        inputValue : state.inputValue
    }
}

const dispatchToProps = (dispatch) = >{
    return {
        inputChange(e){
            console.log(e.target.value)
        }
    }
}
 
export default connect(stateToProps,dispatchToProps)(TodoList);
Copy the code

distributedactionIn the store

The mapping relationship has been done, and the next step is to distribute actions and compile business logic on reducer. Distribute the action the same as before, and I’ll just give you the code.

const dispatchToProps = (dispatch) = >{
    return {
        inputChange(e){
            let action = {
                type:'change_input'.value:e.target.value
            }
            dispatch(action)
        }
    }
}
Copy the code

After distribution, the corresponding business logic was compiled in the Reducer.

const defalutState = {
    inputValue : 'jspang'.list :[]
}
export default (state = defalutState,action) =>{
    if(action.type === 'change_input') {let newState = JSON.parse(JSON.stringify(state))
        newState.inputValue = action.value
        return newState
    }
    return state
}
Copy the code

Once the whole process is complete, check it out in your browser and you should have changed the input field. This process may seem confusing to you at first, but as you do it more often, you will find that it is very simple, just a pattern, and will reduce the chances of errors. It is recommended that you write this process at least five times. As far as I know, almost all companies use React – Redux. Therefore, this process is no less important than redux process.

P23: Advanced-react-redux adds List data

React-redux: React-redux: React-redux: React-redux: React-redux: React-redux What we’re going to do in this video is, when you click submit, you can add to the list.

to<button>Button adds click events

Add an onClick event to/SRC/todolist. js Button.

<button onClick={this. Props. ClickButton} > submit < / button >Copy the code

Notice that we’re still using props, so we also need to put the method in dispatchToProps. Let’s write a test here to see if it’s bound.

const dispatchToProps = (dispatch) = >{
    return {
        inputChange(e){
            let action = {
                type:'change_input'.value:e.target.value
            }
            dispatch(action)
        },
        clickButton(){
            console.log('111111111')}}}Copy the code

After writing the clickButton method, preview it in your browser, open your browser’s console and take a look at the results. When you click, you should see 111111111 displayed. This completes the dispatch of the action with dispatch.

clickButton(){
    let action = { type:'add_item' }
    dispatch(action)
}
Copy the code

writeReducerThe business logic of

After dispatching, compile business logic on Reducer, which is basically the same as the same operation.

const defalutState = {
    inputValue : 'jspang'.list :[]
}

export default (state = defalutState,action) =>{
    if(action.type === 'change_input') {let newState = JSON.parse(JSON.stringify(state))
        newState.inputValue = action.value
        return newState
    }
    //---- key code ------start---------
    if(action.type === 'add_item') {let newState = JSON.parse(JSON.stringify(state))
        newState.list.push(newState.inputValue)
        newState.inputValue = ' '
        return newState
    }
    //---- key code ------end---------
    return state
}
Copy the code

Page UI part of the production

After this step, we went to Todolist. js to write the JSX part. Before writing, we needed to do the mapping of stateToProps well.

const stateToProps = (state) = >{
    return {
        inputValue : state.inputValue,
        list:state.list
    }
}
Copy the code

With the mapping relationship, you can display the interface in the way of attributes, the code is as follows:

<ul>
    {
        this.props.list.map((item,index) = >{
            return (<li key={index}>{item}</li>)
        })
    }
</ul>
Copy the code

In this way, TodoList list items are added. Todolist.js code is given here for easy learning and use.

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

class TodoList extends Component {
    constructor(props){
        super(props)
        this.state = store.getState()
    }
    render() { 
        return (
            <div>
                <div>
                    <input value={this.props.inputValue} onChange={this.props.inputChange} />
                    <button onClick={this.props.clickButton}>submit</button>
                </div>
                <ul>
                    {
                        this.props.list.map((item,index)=>{
                            return (<li key={index}>{item}</li>)})}</ul>
            </div>); }}const stateToProps = (state) = >{
    return {
        inputValue : state.inputValue,
        list:state.list
    }
}

const dispatchToProps = (dispatch) = >{
    return {
        inputChange(e){
            let action = {
                type:'change_input'.value:e.target.value
            }
            dispatch(action)
        },
        clickButton(){
            let action = {
                type:'add_item'
            }
            dispatch(action)
        }
    }
}
export default connect(stateToProps,dispatchToProps)(TodoList);
Copy the code

There’s also a delete feature that I’m not going to waste your time on, but if you’re interested you can try it out. Next time we’ll focus on optimizing the current code so you can look more professional at work.

P24: React-Redux optimization (end)

This class now write code optimization, programs should have some code cleanliness, to write a program praised by people. Code optimization after writing business logic is also one of the essential work of programmers.

Copy compact code with structure

There are several instances in the code where this. Props are repeated, so you can use javascript’s destruct assignment method to simplify the code. Modify the Render function in todolist. js with the following code:

    render() { 
        let {inputValue ,inputChange,clickButton,list} = this.props;
        return (
            <div>
                <div>
                    <input value={inputValue} onChange={inputChange} />
                    <button onClick={clickButton}>submit</button>
                </div>
                <ul>
                    {
                        list.map((item,index)=>{
                            return (<li key={index}>{item}</li>)})}</ul>
            </div>
        );
    }

Copy the code

theTodoListChange to UI components – improve performance

As you can see, the TodoList component doesn’t have any business logic, just a Render method, so you can change it to the UI component (stateless component). The UI component is a method that reduces a lot of redundant operations and improves application performance. Redeclare a TodoList variable, copy the render function, and with a little modification, get the following code:

const TodoList =(props) = >{
    let {inputValue ,inputChange,clickButton,list} = props; // After pasting it, you need to modify it here
    return (
        <div>
            <div>
                <input value={inputValue} onChange={inputChange} />
                <button onClick={clickButton}>submit</button>
            </div>
            <ul>
                {
                    list.map((item,index)=>{
                        return (<li key={index}>{item}</li>)})}</ul>
        </div>
    );
}
Copy the code

Once the code is written, we remove any unnecessary intrusions and preview it in the browser.

import React from 'react';
import {connect} from 'react-redux'
Copy the code

For the sake of learning, I present all the current todolist.js code here.

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


const TodoList =(props) = >{
    let {inputValue ,inputChange,clickButton,list} = props; // After pasting it, you need to modify it here
    return (
        <div>
            <div>
                <input value={inputValue} onChange={inputChange} />
                <button onClick={clickButton}>submit</button>
            </div>
            <ul>
                {
                    list.map((item,index)=>{
                        return (<li key={index}>{item}</li>)})}</ul>
        </div>
    );
}


const stateToProps = (state) = >{
    return {
        inputValue : state.inputValue,
        list:state.list
    }
}

const dispatchToProps = (dispatch) = >{
    return {
        inputChange(e){
            let action = {
                type:'change_input'.value:e.target.value
            }
            dispatch(action)
        },
        clickButton(){
            let action = {
                type:'add_item'
            }
            dispatch(action)
        }
    }
}
export default connect(stateToProps,dispatchToProps)(TodoList);
Copy the code

So let’s go the other way and see what that last sentence means.

export default connect(stateToProps,dispatchToProps)(TodoList);
Copy the code

Connect separates the UI components (stateless components) from the business logic code, and then links them back together through Connect to make the code cleaner and easier to maintain. This is the biggest advantage of React-Redux.

Redux’s tutorial and video ends here. In the next course, I will talk about React-Router. Please keep checking the blog for the latest learning videos.