preface

I haven’t updated my blog for a long time. I have been preparing for spring recruitment for some time. Fortunately, I can work in a good company, whose technology stack is REACT.

I. Introduction to Redux

Redux is a predictable state container for JavaScript applications.

It helps you write applications that perform consistently, run in different environments (client, server, and native), and are easy to test. Most importantly, it provides a great developer experience, such as real-time code editing with a time-traveling debugger.

You can use Redux with React or any other similar tool library. It is small in size (only 2kB counting dependencies), but has a large number of plug-ins available in its ecosystem.

Vuex is a state manager that allows components to share global data when building large applications. Because if the business is too complex, data transfer between components can be cumbersome. And just like that, the left side has no Redux, and the right side has Redux.

Redux workflow

Let’s start with a picture to get a feel for it

2.1 redux installation

NPM install

npm install --save redux
Copy the code

2.2 Basic Use of REdux

React Components get data from the React Components Store. The React Components Store is a data management center where all global data is stored.

We created two files named index.js reducer.js under the store folder in the react project SRC file

The general catalog is as follows

--src
----store
------index.js
------reducer.js
----index.js
----TodoList.js
Copy the code
// store/reducer.js
const defaultState = {
    inputValue: ' '.data: [{id: 1.title: 'eat'.compeled: false },
        { id: 2.title: 'sleep'.compeled: false },
        { id: 3.title: 'Beat the beans'.compeled: false}}]//eslint-disable-next-line
export default (state = defaultState, action) => {

    // console.log(action)
    The Reducer can only receive state but cannot change state
    if(action.type === 'CHANGE_INPUT') {let newValue = JSON.parse(JSON.stringify(state))
        newValue.inputValue = action.value
        return newValue
    }

    if(action.type === 'ADD_ITEM') {let newValue = JSON.parse(JSON.stringify(state))
        if(newValue.inputValue === ' ') return newValue
        let item = {
            id:new Date().getTime(),
            title:newValue.inputValue,
            compeled:false
        }
        newValue.data.push(item)
        newValue.inputValue = ' '
        return newValue
    }

    if(action.type === 'DELETE_ITEM') {let newValue = JSON.parse(JSON.stringify(state))
        let index = newValue.data.findIndex(item= > item.id === action.id)
        newValue.data.splice(index,1)
        return newValue
    }
    
    return state
}
Copy the code
// store/index.js
import {createStore} from 'redux'
import reducer from './reducer'
// reducer (state,action) => {}
const store = createStore(reducer)
export default store
Copy the code

Here we see that creating a store object actually calls the createStore method in REdux. Its parameters are a function (reducer, Reducer) with state and action. State we initialized the value. And what’s going to be in our action?

Taking a look at the todolist.js code, we get the data through store.getState() by importing the store created.

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

import store from './store'

class TodoList extends Component {
    constructor(props) {
        super(props);
      	// Get data
        this.state = store.getState()
      	// Monitor data changes update state
        store.subscribe(this.storeChange)
    }

    deleteItem = (id) = > {
        // console.log(id)
        const action = {
            type:'DELETE_ITEM',
            id
        }
        / / delete the item
        store.dispatch(action)
    }

    handleInputValue = (e) = > {
        const action = {
            type:'CHANGE_INPUT'.value:e.target.value
        }
        / / change inputvalue
        store.dispatch(action)
    }

    clickBtn = () = > {
        const action = {
            type:'ADD_ITEM'
        }
        / / add item
        store.dispatch(action)
    }

    storeChange = () = > {
        this.setState(store.getState())
    }

    render() {
        return (
            <div style={{margin:'15px'}} >
                <div>
                    <Input
                        placeholder='Write Something' 
                        style={{width:'250px',marginRight:'15px'}} 
                        onChange={this.handleInputValue}
                        value={this.state.inputValue}
                    />
                    <Button 
                        type='primary'
                        onClick={this.clickBtn}
                    >Add</Button>
                </div>
                <div style={{marginTop:'15px',width:'250px'}} >
                    <List
                        bordered
                        dataSource={this.state.data}
                        renderItem={item= > (<List.Item onClick={this.deleteItem.bind(this,item.id)}>{item.title}</List.Item>)} / ></div>
            </div>); }}export default TodoList;
Copy the code

The action object must have a type property that tells Redux what kind of action you want to do. That is, we case to that type and execute the corresponding logic. We then updated the data using the Reducer callback. Note here: The reducer can only receive state but not change state, so we can see that the data is copied first and then returned after update, instead of updating state data directly

Then we can have a preliminary understanding of the redux execution process according to the above flow chart. First, create a store object through the createStore function of Redux. Note that the parameter of createStore is a reducer function. React Components fetch data from store.getState(). If we need to operate on a store, we need to dispatch events via store.dispatch(Action). Tell the Store to make a change. How do you make a change? We saw that data was processed through React Components, Action Creators, Store, and finally Reducers, which was called reducer. Therefore, the above code can clearly show that the Reducer function processes events distributed by various dispatches (actions) according to different types. The newState after processing is updated to the Store data warehouse for use by React Components

For ease of reading, let me show you the picture again.

The SRC /index.js code is pasted here for demo integrity

import React from 'react'
import ReactDom from 'react-dom'
import TodoList from './TodoList'

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

That’s about it for the simplest use of Redux. We will continue to update some advanced usage, please remember to pay attention.