react-redux starter version - everything you want to know is here

1. What is redux?

  • reduxIt is an independent, open source, third-party centralized state manager.
  • reduxIn addition to Reactbeing used with and, other interface libraries are also supported. It's small and compact (only 2kB, including dependencies)
  • We know that reactit is a single-item data flow framework, and statethe data has a read-only attribute. In component communication:
    parent to child: pass directly prop,
    child to parent: pass from parent to child method, child component calls this method to pass parameters,
    child pass Child: Brothers pass parameters, state promotion, they can promote their state to the public parent component or use to exentBuscreate a public container.
  • So how to pass parameters for more complex component relationships? If a certain state component needs to be shared by all other components, does every component need to pass parameters and receive parameters? Therefore, in order to solve this problem, we provide us with reduxa A repository where shared state can be stored.

Let's take a look at the working principle diagram of redux

insert image description here

2. The core concept of redux:

Core concepts: store, action,reducer

2.1 store

store: warehouse, the core of Redux, integrating action and reducer
Features:

  • An application has and can only have one store. The data that the entire application needs to manage is in this Store. The object associated with the reducer.
  • We can't change this Store directly, we can only change it by returning a new Store. Redux provides a createStore to create state
import {
    
     createStore } from 'redux'
const store = createStore(reducer)

action: Action
A js object that contains two attributes:

  • type: Identification attribute, the value is a string. Multiple types are separated by action
  • payload: data attribute, optional. Indicates the data carried by this action
  • This action refers to an operation initiated by the view layer to tell the Store that we need to change. For example, if the user clicks the button, we will request the list, and the data in the list will change. Each action must have a type attribute, which indicates the name of the action, and then there can also be a payload attribute, which can take some parameters for Store changes:
const action = {
    
    
  type: 'ADD_ITEM',
  payload: 'new item', // 可选属性
}

reducer: processor

  • initialization state

  • Modify status

  • In redux, reducers are pure functions used to process actions. When an action occurs, the reducers will update the state in the store according to the type and payload in the action. Reducers take the current state and action and return a new state without modifying the original state.

  • Reducers are designed to be pure functions, so they don't have side effects and don't change the arguments passed to them. They always use the same input to produce the same output, so are very easy to test and debug.

  • For example, like a calculator, we need to add 1 to the original data, then the old state corresponds to the original data, and the action corresponds to the operation of adding 1, and the new state returned is the result returned by the calculator after the addition is completed.

The case of defining addition and subtraction in reduce

 reducers: {
    
    
    // 处理加法
    increment: (state) => {
    
    
      state.value += 1;
    },
    // 处理减法
    decrement: (state) => {
    
    
      state.value -= 1;
    },
    addValue: (state, action) => {
    
    
      // action.payload为传入的参数
      state.value += action.payload;
    },
  },

3. Use redux

3.1 Installation depends on @reduxjs/toolkit

npm i @reduxjs/toolkit react-redux -S

3.2 Specific configuration of redux code

1. Define the warehouse
Create a warehouse in the store folder in src, and edit the warehouse in this folder
The following is the case of index.js in the store

// 引入configureStore 定义仓库
import {
    
     configureStore } from "@reduxjs/toolkit";

// 定义仓库
export const store = configureStore({
    
    
  // 数据处理器
  reducer: {
    
    },
});

2. Globally inject the warehouse into
main.js to import the warehouse, import the Provider
and wrap the App with the Provider tag

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './index.css'

// 导入仓库
import {
    
     store } from './store/index'
// 导入provider
import {
    
     Provider } from 'react-redux'
ReactDOM.createRoot(document.getElementById('root')).render(
  // <React.StrictMode>
  <Provider store={
    
    store}>
    <App />
  </Provider>
  // </React.StrictMode>,
)

3. Define warehouse fragment
Create counterSlice.js slice file in store file
createSliceSlice function
nameSlice name
initialStateInitial state
reducersProcessor
Export processor and slice
Export asynchronous operation

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

4. Register the warehouse fragment
and import and inject it in store–>index.jscounterSlice

// 引入configureStore 定义仓库
import {
    
     configureStore } from "@reduxjs/toolkit";
// 导入切片
import counter from "./counterSlice";
// 定义仓库
export const store = configureStore({
    
    
  // 数据处理器
  reducer: {
    
    
    // 注册切片 键值对一致的简写
    counter,
  },
});

5. Use warehouse data
import useSelect, useDispatch, methods defined in
import : , , methods in calls via (method())counterSliceincrenmentdecrementaddValue
dispatchcounterSlice

import {
    
     useSelector, useDispatch } from 'react-redux'
// 导入动作
import {
    
     increment, decrement, addValue } from '@/store/counterSlice'

function DashView() {
    
    
    // 从store中获取数据
    const value = useSelector((state) => state.counter.value)
    // 获取dispatch
    const dispatch = useDispatch()

    return (<>
        <h1>DashView页面 counter的值:{
    
    value}</h1>
        <button onClick={
    
    () => dispatch(increment())}>+1</button>
        <button onClick={
    
    ()=>dispatch(decrement())}>-1</button>
        <button onClick={
    
    ()=>dispatch(addValue(5))}>+5</button>
    </>);
}
export default DashView;

The above is the basic knowledge of rudux.

Guess you like

Origin blog.csdn.net/promise466/article/details/130026429