Redux working principle, workflow and code details (application in React)

Redux working principle, workflow and code details in React

What is redux?
To put it simply, there are two points
1. Redux is a JS library specially used for state management. It is not a react plug-in library, but it is basically developed in conjunction with react. Use
2. Its function: Centrally manage the state shared by multiple components in react applications, and be responsible for managing the state.
When do you need to use redux?
1. The status of a certain component needs to be shared by other components at any time.
2. One component needs to change the status (or communication) of another component.
Simply draw the redux schematic diagram:
Insert image description hereThe following uses a small demo of summation to demonstrate the code of redux: realizing addition, subtraction, odd addition, and asynchronous addition< /span> 1. Install redux:
Detailed code explanation:

yarn add redux

1. Create a new action.js and name it yourself: this file specifically generates action objects for the Count component.

//该文件专门为Count组件生成action对象
import{
    
    INCREMENT,DECREMENT} from './constant'
//加法
export function createIncrementAction(data){
    
    
    return {
    
    type:INCREMENT,data:data}
}
//简约写法:
// export const createIncrementAction = data =>({type:'increment',data:data})
//减法
export function createDecrementAction(data){
    
    
    return {
    
    type:DECREMENT,data:data}
}

2. **(Core)** Create a new store.js and name it yourself: this file is specifically used to expose a store object, and there is only one store object in the entire application.

// 该文件专门用于暴露一个store对象,整个应用只有一个store对象

//引入createStore,专门用于创建redux中最为核心的store对象
// import {createStore} from 'redux'
//createStore已经启用改用:
import {
    
    legacy_createStore as createStore} from 'redux'

//引入为Count组件服务的reducer
import countReducer from './count_reducer'

//store暴露出去
export default createStore(countReducer)

3. Just name the new reducer.js yourself: this file is used to create a reducer that serves the Count summation component. The essence of the reducer is a function.

// 1.该文件用于创建一个为Count组件服务的reducer、reducer本质就是一个函数
//2.reducer函数会接收到两个参数,分别为:之前的状态(preState),动作对象(action)
import{
    
    INCREMENT,DECREMENT} from './constant'
export default function countReducer(preState, action) {
    
    
    console.log(preState)
    //初始化判断
    if(preState===undefined) preState = 0
    //从action对象中获取type和date
    const {
    
     type, data } = action
    //根据type决定如何加工数据
    switch (type) {
    
    
        case INCREMENT:
            return preState + data//加
        case DECREMENT:
            return preState - data//减
        default:
            return preState
    }
}

4. (You don’t have to) Create a new constant.js and name it yourself: This file is used to define the constant value of the type type in the action object (standardized development, it is recommended to also centrally manage redux-related constants)

//该文件是用于定义action对象中type类型的常量值
//目的为了便于同时管理action的动作对象,可以不用
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'

5. Count summation component code:

import React, {
    
     Component } from 'react'
//引入store,用于获取redux中保存的状态
import store from '../../redux/store'
//引入actionCreator,专用于创建action对象
import {
    
    createDecrementAction,createIncrementAction} from '../../redux/count_action'

export default class Count extends Component {
    
    
    state = {
    
     myState: '自身独有的state' }

    componentDidMount() {
    
    
        //监测redux中状态的变化,只要变化,就调用render()
        store.subscribe(() => {
    
    
            //此处作用是为了更新render,即执行setState就会触发render
            this.setState({
    
    })
        })
    }
    //加法
    increment = () => {
    
    
        const {
    
     value } = this.selectNumber
        //自己创建的action
        // store.dispatch({ type: 'increment', data: value * 1 })
        //通过actionCreator创建的action
        store.dispatch(createIncrementAction(value*1))
    }
    //减法
    decrement = () => {
    
    
        const {
    
     value } = this.selectNumber
        store.dispatch(createDecrementAction(value*1))
    }
    //奇数再加
    incrementIfOdd = () => {
    
    
        const {
    
     value } = this.selectNumber
        const count = store.getState()
        if (count % 2 !== 0) {
    
    
            store.dispatch(createDecrementAction(value*1))
        }
    }
    //异步加
    incrementAsyc = () => {
    
    
        const {
    
     value } = this.selectNumber
        setTimeout(()=>{
    
    
            store.dispatch(createDecrementAction(value*1))
        },500)
    }
    render() {
    
    
        return (
            <div>
                <h1>当前求和为:{
    
    store.getState()}</h1>
                <select ref={
    
    c => this.selectNumber = c}>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                </select>&nbsp;
                <button onClick={
    
    this.increment}>+</button>&nbsp;
                <button onClick={
    
    this.decrement}>-</button>&nbsp;
                <button onClick={
    
    this.incrementIfOdd}>当前求和为奇数再加</button>&nbsp;
                <button onClick={
    
    this.incrementAsyc}>异步加</button>&nbsp;
            </div>
        )
    }
}

6. App.jsx code:

import React, {
    
     Component } from 'react'
import Count from './components/Count'

export default class App extends Component {
    
    
  render() {
    
    
    return (
      <div>
        <Count/>
      </div>
    )
  }
}

Instructions:
1. store.js:
(1) Introduce legacy_createStore in redux (note: createStore has been abandoned) and create a store
(2) When legacy_createStore is called, a reducer that serves it must be passed in
(3) Expose the store object
2. reducer.js:
(1) This file is used to create a reducer that serves the Count component. The reducer is essentially a function that receives preState, action, and returns the processed state< a i=7> (2) The reducer has 2 functions: initialization function and processing status (3) When the reducer is called for the first time, it is triggered by the store, The passed preState is undefined, The passed action is data in the following format: {type: “@@redux/INITr.y.u.u.5.o” } 3. action.js: This file specifically generates action objects for the components it serves. 4. constant.js: unified management of related constants in actions. At the same time, avoid writing wrong constant fields 5. Note: You can monitor the state changes in the store in the index.js entry file, and re-render once changes occur Code As follows: Original:









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

After adding monitoring: remember to introduce store

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

Supplement:
redux is only responsible for managing the state. As for the change of state that drives the display of the page, we need to implement it ourselves

Done, brother, try it now! ! !

Guess you like

Origin blog.csdn.net/qq_41497443/article/details/124901967