A detailed introduction to how to use redux in React

Before using it, you need to understand its supporting plug-ins:

To use redux in React, the official requirement is to install other plugins Redux Toolkit and react-redux

  1. Redux Toolkit: It is an officially recommended toolset designed to simplify the use and management of Redux. Redux Toolkit provides some tools and features to improve development efficiency, such as  createSlice and  configureStore, making it easier to write and organize Redux code. With Redux Toolkit, you can write Redux code faster while still getting some performance optimizations and development convenience.

    Install Redux Toolkit:

npm install @reduxjs/toolkit

  1. react-redux: It is a library officially provided by Redux for integration with React. It provides  Provider components to inject the Redux store into the entire React application, as well as  useDispatch these  useSelector convenient hook functions for using Redux's dispatch and selector functions in React components.

    Install react-redux:

npm install react-redux

After installing these two plugins, you can use Redux in your React application and use the Redux Toolkit for more concise and efficient coding, while integrating easily with React through react-redux.

Create a new react file, and after installing the two plugins, adjust the directory structure

image.png

start using:

Step 1: Initialize the state, define the method to modify the state, deconstruct the actionCreater function, and obtain the reducer

reducers are used to define how to update the state of the application. It receives two parameters: the current state (state) and the action to be executed, and returns a new state.

counterStore.js

import {
    
     createSlice } from "@reduxjs/toolkit";

const counterStore = createSlice({
    
    
  name: "counter",
  
  // 初始化 state
  initialState: {
    
    
    count: 0,
  },
  
  // 修改状态的方法 同步方法,可以直接修改值
  reducers: {
    
    
    addCount(state) {
    
    
      state.count++;
    },
    decreaseCount(state) {
    
    
      state.count--;
    },
  },
});

// 解构出来 actionCreater函数
const {
    
     addCount, decreaseCount } = counterStore.actions;
// 获取 reducer
const reducer = counterStore.reducer;
// 按需导出
export {
    
     addCount, decreaseCount };
// 默认导出
export default reducer;

Step 2: Export redux in export file

src\store\index.js

// 出口文件
import {
    
     configureStore } from "@reduxjs/toolkit";
// 导入子模块
import counterStore from "./modules/counterStore";

const store = configureStore({
    
    
  reducer: {
    
    
    counter: counterStore,
  },
});

// 导出
export default store;

Step 3: Configure the data in redux to be globally available

src\index.js

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
// Redux
import store from "./store";
import {
    
     Provider } from "react-redux";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    {
    
    /* 全局可用 */}
    <Provider store={
    
    store}>
      <App />
    </Provider>
  </React.StrictMode>
);

reportWebVitals();

Step Four: Use

useDispatch: It simplifies the process of using the dispatch function in the function component, without manually obtaining the dispatch function from the store.

useSelector: It allows the component to select the desired state from the Redux store. Through it, you can subscribe to the state of the Redux store to get the required data in the component.

App.js

import "./App.css";
import {
    
     useDispatch, useSelector } from "react-redux";
// 获取
import {
    
     addCount, decreaseCount } from "./store/modules/counterStore";

function App() {
    
    
  // 得到 Redux 中的数据
  const {
    
     count } = useSelector((state) => state.counter);
  // 处理数据的函数
  const dispatch = useDispatch();
  return (
    <div className="App">
      <button onClick={
    
    () => dispatch(addCount())}>+</button>
      <p>{
    
    count}</p>
      <button onClick={
    
    () => dispatch(decreaseCount())}>-</button>
    </div>
  );
}

export default App;

carry parameters

 // 接收传参
    addTonum(state, action) {
    
    
      // action.payload 可以获取到传入的参数
      state.count = action.payload;
    },
import {
    
     createSlice } from "@reduxjs/toolkit";

const counterStore = createSlice({
    
    
  name: "counter",
  // 初始化 state
  initialState: {
    
    
    count: 0,
  },
  // 修改状态的方法 同步方法,可以直接修改值
  reducers: {
    
    
    addCount(state) {
    
    
      state.count++;
    },
    decreaseCount(state) {
    
    
      state.count--;
    },
    // 接收传参
    addTonum(state, action) {
    
    
      // action.payload 可以获取到传入的参数
      state.count = action.payload;
    },
  },
});

// 解构出来 actionCreater函数
const {
    
     addCount, decreaseCount, addTonum } = counterStore.actions;
// 获取 reducer
// 用于定义如何更新应用的状态。它接收两个参数:当前的状态(state)和即将执行的 action,并返回一个新的状态。
const reducer = counterStore.reducer;

// 按需导出
export {
    
     addCount, decreaseCount, addTonum };
// 默认导出
export default reducer;

App.js

      <button onClick={
    
    () => dispatch(addTonum(10))}>+10</button>
      <button onClick={
    
    () => dispatch(addTonum(20))}>+20</button>

asynchronous request section

Implementation of asynchronous encapsulation

1. The writing method of creating a store remains unchanged, and the method of synchronously modifying the state is configured

2. Encapsulate a function separately, return a new function inside the function, and in the new function

2.1 Encapsulate asynchronous request to obtain data

2.2 Call synchronous actionCreater to pass in asynchronous data to generate an action object and submit it using dispatch

3. The writing method of dispatch in the component remains unchanged

src\store\modules\channelStore.js

// 异步封装的实现
import {
    
     createSlice } from "@reduxjs/toolkit";
import axios from "axios";

const channelStore = createSlice({
    
    
  name: "channel",
  
  // 初始值
  initialState: {
    
    
    channelList: [],
  },
  reducers: {
    
    
    setChannels(state, action) {
    
    
      state.channelList = action.payload;
    },
  },
});

  
// 异步请求部分
// http://geek.itheima.net/v1_0/channels
const {
    
     setChannels } = channelStore.actions;

const fetchChannlList = () => {
    
    
  return async (dispatch) => {
    
    
    const res = await axios.get("http://geek.itheima.net/v1_0/channels");
    dispatch(setChannels(res.data.data.channels));
  };
};

export {
    
     fetchChannlList };

const reducer = channelStore.reducer;
export default reducer;

Export File

src\store\index.js

// 出口文件
import {
    
     configureStore } from "@reduxjs/toolkit";
// 导入子模块
import counterStore from "./modules/counterStore";
import channelStore from "./modules/channelStore";

const store = configureStore({
    
    
  reducer: {
    
    
    counter: counterStore,
    channel: channelStore,
  },
});

// 导出
export default store;

use

App.js

import "./App.css";
import {
    
     useEffect } from "react";

import {
    
     useDispatch, useSelector } from "react-redux";
// 获取
import {
    
    
  addCount,
  decreaseCount,
  addTonum,
} from "./store/modules/counterStore";
import {
    
     fetchChannlList } from "./store/modules/channelStore";

function App() {
    
    
  // 得到 Redux 中的数据
  const {
    
     count } = useSelector((state) => state.counter);
  const {
    
     channelList } = useSelector((state) => state.channel);

  // 处理数据的函数
  const dispatch = useDispatch();
  // 挂载渲染
  useEffect(() => {
    
    
    dispatch(fetchChannlList());
  }, [dispatch]);
  return (
    <div className="App">
      <button onClick={
    
    () => dispatch(addCount())}>+</button>
      <p>{
    
    count}</p>
      <button onClick={
    
    () => dispatch(decreaseCount())}>-</button>
      <hr />
      {
    
    /* redux 传入参数 */}
      <button onClick={
    
    () => dispatch(addTonum(10))}>+10</button>
      <button onClick={
    
    () => dispatch(addTonum(20))}>+20</button>
      <hr />
      {
    
    /* 异步 */}
      <ul>
        {
    
    channelList.map((item) => (
          <li key={
    
    item.id}>{
    
    item.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;

Browser plugin, manage redux

Redux DevTools

Guess you like

Origin blog.csdn.net/wbskb/article/details/131998390