当前位置:网站首页>Redux learning (I) -- the process of using Redux

Redux learning (I) -- the process of using Redux

2022-06-11 06:29:00 Xiaobai learns computer

One 、 Why redux

  • JavaScript Developed applications , It has become more and more complex :
  1. JavaScript More and more states need to be managed , More and more complex ;
  2. These states include the data returned by the server 、 Cache data 、 Data generated by user operation, etc , It also includes some UI The state of , For example, whether some elements are selected ,
    Whether to display the loading dynamic effect , Current page ;
  • Manage changing state It's very difficult :
  1. There will be dependencies between States , A change in one state will cause a change in another state ,View Pages can also cause state changes ;
  2. When the application is complex ,state when , For what reason has it changed , What changes have taken place , Will become very difficult to control and track ;
  • React It was at the view level that helped us solve DOM The rendering process , however State It is still left to us to manage :
  1. Whether the component defines its own state, Or the communication between components is through props To pass ; It also includes the adoption of Context Share data ;
  2. React Mainly responsible for helping us manage views ,state How to maintain it is ultimately up to us to decide ;
     Insert picture description here
  • Redux Is one that helps us manage State The container of :Redux yes JavaScript The state container of , Provides predictable state management ;

  • Redux Except for and React In addition to being used together , It can also be used with other interface libraries ( such as Vue), And it's very small ( Including dependencies , Only 2kb)

Two 、Redux Core concept of - Store

Redux The core idea of is very simple .

  • For example, we have a list of friends to manage :
  1. If we don't define a unified specification to operate this data , Then the change of the whole data cannot be tracked ;
  2. For example, somewhere on the page passes products.push A piece of data is added in the way of ;
  3. For example, another page passes products[0].age = 25 Modified a piece of data ;

The entire application is intricate , When there is a bug when , It's hard to track exactly where the changes are happening ;
 Insert picture description here

3、 ... and 、Redux Core concept of - action

Redux Ask us to pass action To update the data :

  • Changes in all data , It has to be distributed (dispatch)action To update ;
  • action It's a common JavaScript object , Used to describe this update type and content;

For example, here are some updates friends Of action:

  • Compulsory use action The advantage is that you can clearly know what changes have taken place in the data , All data changes are traceable 、 Predictable ;
  • Of course , At present, our action Is a fixed object , In real application , We will define by function , Return to one action;

 Insert picture description here

Four 、Redux Core concept of - reducer

But how will state and action It's connected ? The answer is reducer

  • reducer It's a pure function ;
  • reducer What you do is bring in state and action Combine to create a new state;

 Insert picture description here

5、 ... and 、Redux Three principles of

  1. Single data source
  • Of the entire application state Is stored in a object tree in , And this object tree Only stored in one store in :
  • Redux There is no compulsion that prevents us from creating multiple Store, But that's not good for data maintenance ; p A single data source can make the whole application state Become easy to maintain 、 track 、 modify ;
  1. State Is read-only
  • Unique modification State The method must be trigger action, Don't try to modify... In any way elsewhere State:
  • This ensures that View Or network requests cannot be modified directly state, They can only pass through action To describe how you want to modify state;
  • This ensures that all changes are centralized , And execute in strict order , So don't worry about race condition( Unexpectedly state ) The problem of ;
  1. Use pure functions to perform modifications
  • adopt reducer take used state and actions Connect , And return to a new State:
  • As the complexity of the application increases , We can reducer Break it up into smaller ones reducers, Operate differently state tree Part of ;
  • But all reducer Should be pure functions , No side effects ;

6、 ... and 、Redux Process of use

  1. Create an object , As the state we want to save :
  2. establish Store To store this state
  • establish store Must be created when reducer;
  • We can go through store.getState To get the current state
  1. adopt action To modify the state
  • adopt dispatch To distribute action;
  • Usually action There will be type attribute , You can also carry other data ;
  1. modify reducer Processing code in
  • Remember here ,reducer It's a pure function , No direct modification is required state; - I will talk about direct modification later state The problems brought about by ;
  1. You can distribute action Before , monitor store The change of :
     Insert picture description here
const redux = require('redux')
const initalState = {
    
    counter: 0
}
// reducer
function reducer(state = initalState, action) {
    
    switch (action.type) {
    
        case 'INCREMENT':
            return {
    ...state, counter: state.counter + 1}
        case 'DECREMENT':
            return {
    ...state, counter: state.counter - 1}
        case 'ADD_NUMBER':
            return {
    ...state, counter: state.counter + action.num}
        case 'SUB_NUMBER':
            return {
    ...state, counter: state.counter - action.num}
        default:
            return state
    }
}

// store
const store = redux.createStore(reducer)

//  subscribe store Modification of 
store.subscribe(() => {
    
    console.log('counter: ', store.getState().counter)
})

// action
const action1 = {
    type: 'INCREMENT'}
const action2 = {
    type: 'DECREMENT'}
const action3 = {
    type: 'ADD_NUMBER', num: 5}
const action4 = {
    type: 'SUB_NUMBER', num: 12}

//  distributed action
store.dispatch(action1)
store.dispatch(action2)
store.dispatch(action3)
store.dispatch(action4)



7、 ... and 、Redux Structure division

If we put all the logic code together , So when redux Code becomes difficult to maintain when it becomes complex .

Next , I will split the code , take store、reducer、action、constants Split into files .

  1. establish store/index.js file :
  2. establish store/reducer.js file :
  3. establish store/actionCreators.js file :
  4. establish store/constants.js file :

 Insert picture description here

Be careful :node Chinese vs ES6 Modular support
 Insert picture description here

  • Currently I use node The version is v14.16.1, from node v13.2.0 Start ,node That's right ES6 Modularity provides support :
  • node v13.2.0 Before , You need to do the following :
  1. stay package.json Add attributes in : “type”: “module”;

  2. Add the following options to the execute command :node --experimental-modules src/index.js;

  3. node v13.2.0 after , Just do the following :
    stay package.json Add attributes in : “type”: “module”;
    Be careful : When importing a file , We need to keep up .js Suffix name ;

index.js:
 Insert picture description here
store/index.js:
 Insert picture description here
store/actionCreator.js:
 Insert picture description here
store/reducer.js:
 Insert picture description here
store/constants.js:
 Insert picture description here
 Insert picture description here

8、 ... and 、Redux Official picture

 Insert picture description here

Nine 、redux integrate into react Code

at present redux stay react Is the most used in , So we need to put the previously written redux Code , Integrated into the react Go to of .
Here I create two components :

  1. Home Components : It will show the current counter value , And there's a +1 and +5 The button ;
  2. About Components : It will show the current counter value , And there's a -1 and -5 The button ;

 Insert picture description here
The core code is mainly composed of two :
3. stay componentDidMount Changes in data defined in , Reset when data changes counter;
4. When a click event occurs , call store Of dispatch To distribute the corresponding action;
 Insert picture description here

Home.js:

import React, {
    PureComponent} from 'react';
import store from "../store";

import {
    addAction} from "../store/actionCreator";

class Home extends PureComponent {
    
    constructor(props) {
    
        super(props);
        this.state = {
    
            counter: store.getState().counter
        }
    }
    componentDidMount() {
    
        this.unsubscribue = store.subscribe(() => {
    
            this.setState({
    
                counter: store.getState().counter
            })
        })
    }
    componentWillUnmount() {
    
        this.unsubscribue()
    }

    render() {
    
        return (
            <div>
                <h1>Home</h1>
                <h3> Current count :{
    this.state.counter}</h3>
                <button onClick={
    e => this.increment()}>+1</button>
                <button onClick={
    e => this.addNumber(5)}>+5</button>
            </div>
        );
    }
    increment () {
    
        store.dispatch(addAction(1))
    }

    addNumber (num) {
    
        store.dispatch(addAction(num))
    }
}

export default Home;

About.js:

import React, {
    PureComponent} from 'react';
import store from "../store";
import {
    addAction, subAction} from "../store/actionCreator";

class About extends PureComponent {
    
    constructor(props) {
    
        super(props);
        this.state = {
    
            counter: store.getState().counter
        }
    }

    componentDidMount() {
    
        this.unsubscribue = store.subscribe(() => {
    
            this.setState({
    
                counter: store.getState().counter
            })
        })
    }

    componentWillUnmount() {
    
        this.unsubscribue()
    }

    render() {
    
        return (
            <div>
                <h1>About</h1>
                <h3> Current count :{
    this.state.counter}</h3>
                <button onClick={
    e => this.subNumber(1)}>-1</button>
                <button onClick={
    e => this.subNumber(5)}>-5</button>
            </div>
        );
    }
    subNumber (num) {
    
        store.dispatch(subAction(num))
    }
}

export default About;

App.js:

import React, {
    PureComponent} from 'react';
import Home from "./pages/Home";
import About from "./pages/About";

class App extends PureComponent {
    
    render() {
    
        return (
            <div>
                <Home/>
                <hr/>
                <About/>
            </div>
        );
    }
}


export default App;

 Insert picture description here

原网站

版权声明
本文为[Xiaobai learns computer]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203020527105086.html