Detailed explanation of the basic use of Redux (difficulty in kindergarten, as long as you have hands)

Detailed explanation of the basic usage process of Redux

learning documents

Chinese documentation: http://www.redux.org.cn/
English documentation: https://redux.js.org/
Github: https://github.com/reactjs/redux

First, what is redux

1 Introduction:

  1. redux is a 状态管理JS library dedicated to doing things (不是react插件库).
  2. It can be used in react, angular, vueprojects such as 基本与react配合使用.
  3. Role: Centralized management of react applications 多个组件共享的状态.

2. Under what circumstances do you need to use redux

  1. The state of a component needs to be available to other components 随时拿到(共享).
  2. A component needs to change the state of another component ( 通信).
  3. General principle: 能不用就不用, if not used 比较吃力才考虑使用.

3. Redux workflow

insert image description here

Two, the three core concepts of redux

1,action

  1. object of action
  2. Contains 2 attributes
    type: identification attribute, value is string, unique, required attribute
    data: data attribute, value type is arbitrary, optional attribute
  3. Example: { type: 'ADD_STUDENT', data:{name: 'tom', age:18} }

2,reducer

  1. It is used for initialization state and processing state.
  2. During processing, a pure function that generates a new state based on the old state and action.

3,store

  1. The object that ties state, action, and reducer together
  2. How to get this object?
import {
    
    createStore} from 'redux'
import reducer from './reducers'
const store = createStore(reducer)
  1. The function of this object?
    getState(): get state
    dispatch(action): distribute action, trigger reducer call, generate new state
    subscribe(listener): register listener, when a new state is generated, it will be called automatically

Three, the core API of redux

1,createstore()

Function: Create a store object containing the specified reducer

2, store object

  1. Role: the core management object of the redux library
  2. It internally maintains:

state
reducer

  1. Core method:

getState()
dispatch(action)
subscribe(listener)

  1. Specific coding:

store.getState()
store.dispatch({type:‘INCREMENT’, number})
store.subscribe(render)

3,applyMiddleware()

Role: Redux-based middleware (plug-in library) on the application

4,combineReducers()

Role: Merge multiple reducer functions

Fourth, use redux to write applications

1. Install

npm install --save redux

2. Create a new file

Under the src path, create a new store file

insert image description here

3. Define the warehouse:

new src/store/index.js

// 定义仓库
// 引入configureStore 定义仓库
import {
    
     configureStore } from "@reduxjs/toolkit";
// 导入counterSlice
import counter from "./counterSlice";
// 导出
export const store = configureStore({
    
    
  // 数据处理
  reducer: {
    
    
    counter
  }
});

4. How to create counter data and modify data:

New src/store/counterSlice.js

// 创建计数器切片slice
// 导入创建切片的函数
import {
    
     createSlice } from "@reduxjs/toolkit";
// 定义初始化状态
const initialState = {
    
     value: 0 };
// 创建切片
const counterSlice = createSlice({
    
    
  // 切片名称
  name: "counter",
  // 初始化状态
  initialState,
  // 定义处理器
  reducers: {
    
    
    // 处理加法
    increment: state => {
    
    
      state.value += 1;
    },
    // 处理减法
    decrement: state => {
    
    
      state.value -= 1;
    },
    // 处理加法
    addValue: (state, action) => {
    
    
      state.value += action.payload;
    }
  }
});

// 导出动作
export const {
    
     increment, decrement, addValue } = counterSlice.actions;
// 导出处理器
export default counterSlice.reducer;
// 导出异步操作动作
export const syncAddvalue = value => dispatch => {
    
    
  setTimeout(() => {
    
    
    dispatch(addValue(value));
  }, 2000);
};

5. Use redux in components

src/views/ProductView.js file:


import {
    
    
  increment,
  decrement,
  addValue,
  syncAddvalue
} from "../store/counterSlice";
import {
    
     useSelector, useDispatch } from "react-redux";
const ProductView = () => {
    
    
  // 获取仓库数据
  const count = useSelector(state => state.counter.value);
  // 获取修改仓库数据的工具
  const dispatch = useDispatch();
  return (
    <div>
      <p>
        仓库数据:{
    
    count}
      </p>
      <button onClick={
    
    () => dispatch(increment())}>+1</button>
      <button onClick={
    
    () => dispatch(decrement())}>-1</button>
      <button onClick={
    
    () => dispatch(addValue(5))}>+5</button>
      <button onClick={
    
    () => dispatch(syncAddvalue(10))}>两秒后+10</button>
    </div>
  );
};

export default ProductView;

Renderings:

insert image description here

Five, redux asynchronous programming

1. Understand:

  1. Redux cannot perform asynchronous processing by default.
  2. Sometimes the application needs to be in redux中执行异步任务(ajax, timer)

2. Use asynchronous middleware

npm install --save redux-thunk

Six, react-redux

1. understand

  1. A react plugin library
  2. Specifically designed to simplify the use of redux in react applications

2. react-Redux divides all components into two categories

  1. UI components
  1. It is only responsible for the rendering of the UI without any business logic
  2. Receive data through props (general data and functions)
  3. Does not use any Redux API
  4. Generally saved in the components folder
  1. container component
  1. Responsible for managing data and business logic, not responsible for UI presentation
  2. APIs using Redux
  3. Generally saved in the containers folder

3. Related APIs

  1. Provider: Let all components get state data
<Provider store={
    
    store}>
  <App />
</Provider>

  1. connect: Used to wrap UI components to generate container components
import {
    
     connect } from 'react-redux'
  connect(
    mapStateToprops,
    mapDispatchToProps
  )(Counter)

  1. mapStateToprops: converts external data (that is, state objects) into label properties of UI components
const mapStateToprops = function (state) {
    
    
  return {
    
    
    value: state
  }
}

  1. mapDispatchToProps: Convert the function of dispatching action to the label attribute of UI component

Seven, use the redux debugging tool

1. Install the chrome browser plug-in

insert image description here

2. Download the tool dependency package

npm install --save-dev redux-devtools-extension

Eight, pure functions and higher-order functions

1. Pure functions

  1. A special kind of function: As long as it is the same input (actual parameter), it must get the same output (return)
  2. The following constraints must be observed
  1. Do not overwrite parameter data
  2. Does not produce any side effects such as network requests, input and output devices
  3. Impurity methods such as Date.now() or Math.random() cannot be called
  1. The reducer function of redux must be a pure function

2. Higher-order functions

  1. Understanding: a special class of functions

    1. Case 1: The parameter is a function
    2. Case 2: The return is a function
  2. Common higher-order functions:

    1. Timer setting function
    2. Array's forEach()/map()/filter()/reduce()/find()/bind()
    3. promise
    4. The connect function in react-redux
  3. Role: can achieve more dynamic and more scalable functions

    Please add a picture description

Guess you like

Origin blog.csdn.net/m0_64875238/article/details/130029878