Blog
首页
文档
收藏
关于
  • 在线转换时间戳 (opens new window)
  • 在线压缩图片 (opens new window)
  • Float-Double转二进制 (opens new window)
  • 文件转Hex字符串 (opens new window)

HiuZing

🍑
首页
文档
收藏
关于
  • 在线转换时间戳 (opens new window)
  • 在线压缩图片 (opens new window)
  • Float-Double转二进制 (opens new window)
  • 文件转Hex字符串 (opens new window)
  • 前端面试题

  • JavaScript

  • Vue2

  • port

  • CSS

  • Node.js

  • JavaScript优化

  • uniapp

  • Mini Program

  • TypeScript

  • 面向对象编程

  • UI组件

  • Plugin

  • Vue3

  • 性能优化

  • Axios

  • 状态管理

  • React

    • 教程

    • 实战

      • React权限控制
      • React Redux实战
        • 工具
        • 流程
        • 异步操作
        • 基本例子
  • Mock

  • Icon

  • Template

  • 构建工具

  • 项目规范配置

  • Taro

  • SVG

  • React Native

  • 前端
  • React
  • 实战
HiuZing
2023-11-05
目录

React Redux实战

# 工具

  1. Redux Toolkit (opens new window)

    yarn add @reduxjs/toolkit react-redux
    
    1
  2. React Redux (opens new window)

# 流程

  1. useSelector获取store数据
  2. useDispatch获取dispatch方法
  3. 执行store模块中到处的actionCreate方法得到action对象

image-20231105181151770

  1. 使用Redux Toolkit 创建counterStore

    image-20231105193031775

    // counterStore
    import {createSlice} from "@reduxjs/toolkit";
    
    const counterStore = createSlice({
        name: 'counter',
        // 初始化状态
        initialState: {
            value: 0
        },
        // 修改状态的方法 同步方法 支持直接修改
        reducers: {
            increment: (state) => {
                state.value += 1
            },
            decrement: (state) => {
                state.value -= 1
            }
        }
    })
    // 解构出来actionCreate函数
    const {increment, decrement} = counterStore.actions
    // 获取reducer
    const counterReducer = counterStore.reducer
    // 以按需导出的方式导出actionCreate
    export {increment, decrement}
    // 以默认导出的方式到处reducer
    export default counterReducer
    
    
    // index.js
    import {configureStore} from "@reduxjs/toolkit";
    // 导入子模块reducer
    import counterReducer from "./modules/counterStore";
    
    const store = configureStore({
        reducer: {
            counter: counterReducer
        }
    })
    
    export default store
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
  2. 为React注入store(进行连接操作)

    内置provider组件,通过store参数把创建好的store实例注入应用

    import React from 'react';
    import ReactDOM from 'react-dom/client';
    import './index.css';
    import App from './App';
    import reportWebVitals from './reportWebVitals';
    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();
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
  3. 使用store中的数据

    使用钩子函数useSelector,作用是把store中的数据映射到组件

    import {useDispatch, useSelector} from "react-redux";
    // 导入创建action对象的方法
    import {addToNumber, decrement, increment} from "./store/modules/counterStore";
    
    function App() {
        const counter = useSelector(state => state.counter.value);
        // 使用useDispatch方法
        const dispatch = useDispatch();
    
        return (
            <div className="App">
                counter:{counter}
            </div>
        );
    }
    
    export default App;
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
  4. 修改store中的数据

    使用hook函数useDispatch,作用生成提交action对象的dispatch函数

    import {useDispatch, useSelector} from "react-redux";
    // 导入创建action对象的方法
    import {addToNumber, decrement, increment} from "./store/modules/counterStore";
    
    function App() {
        const counter = useSelector(state => state.counter.value);
        // 使用useDispatch方法
        const dispatch = useDispatch();
    
        return (
            <div className="App">
                {/*调用dispatch提交的action对象*/}
                <button onClick={() => dispatch(increment())}>Increment</button>
                counter:{counter}
                <button onClick={() => dispatch(decrement())}>Decrement</button>
            </div>
        );
    }
    
    export default App;
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
  5. 提交action传参

    在reducer的同步方法中添加参数,调用actionCreater的时候传递参数,参数被传到action的payload属性

    import {useDispatch, useSelector} from "react-redux";
    import {addToNumber, decrement, increment} from "./store/modules/counterStore";
    
    function App() {
        const counter = useSelector(state => state.counter.value);
        const dispatch = useDispatch();
    
        return (
            <div className="App">
                <button onClick={() => dispatch(increment())}>Increment</button>
                counter:{counter}
                <button onClick={() => dispatch(decrement())}>Decrement</button>
                {/*提交action传参*/}
                <button onClick={() => dispatch(addToNumber(10))}>add to 10</button>
                <button onClick={() => dispatch(addToNumber(20))}>add to 20</button>
            </div>
        );
    }
    
    export default App;
    
    // couterStore
    import {createSlice} from "@reduxjs/toolkit";
    
    const counterStore = createSlice({
        name: 'counter',
        // 初始化状态
        initialState: {
            value: 0
        },
        // 修改状态的方法 同步方法 支持直接修改
        reducers: {
            addToNumber: (state, action) => {
                state.value = action.payload
            }
        }
    })
    // 解构出来actionCreate函数
    const {increment, decrement, addToNumber} = counterStore.actions
    // 获取reducer
    const counterReducer = counterStore.reducer
    // 以按需导出的方式导出actionCreate
    export {increment, decrement, addToNumber}
    // 以默认导出的方式到处reducer
    export default counterReducer
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45

# 异步操作

  1. 创建store的写法保持不变,配置好同步修改状态的方法,新建channelStore
  2. 单独封装一个函数,在函数内部return一个新函数,在新函数中
    1. 封装异步请求获取数据
    2. 调用同步actionCreater传入异步数据生成一个action对象,并使用dispatch提交
  3. 组件中dispatch的写法保持不变
// channelStore.js
import {createSlice} from "@reduxjs/toolkit";
import axios from "axios";

const channelSlice = createSlice({
    name: 'channel',
    initialState: {
        channelList: [],
    },
    reducers: {
        setChannels: (state, action) => {
            state.channelList = action.payload
        },
    }
})
// action导出
export const {setChannels} = channelSlice.actions
// 异步请求
const fetchChannelList = () => {
    return async (dispatch) => {
        const res = await axios.get('http://geek.itheima.net/v1_0/channels')
        // 使用dispatch提交action
        dispatch(setChannels(res.data.data.channels))
    }
}

export {fetchChannelList}

const reducer = channelSlice.reducer
export default reducer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

在store/index.js

// 导入子模块reducer
import {configureStore} from "@reduxjs/toolkit";

import channelReducer from "./modules/channelStore";

const store = configureStore({
    reducer: {
        channel: channelReducer
    }
})

export default store
1
2
3
4
5
6
7
8
9
10
11
12

在App使用

import {useDispatch, useSelector} from "react-redux";
import {useEffect} from "react";
// 导入创建action对象的方法
import {fetchChannelList} from "./store/modules/channelStore";

function App() {
    const channelList = useSelector(state => state.channel.channelList);
    // 使用useDispatch方法
    const dispatch = useDispatch();
    // 使用useEffect触发异步请求执行
    useEffect(() => {
        dispatch(fetchChannelList())
    }, [dispatch]);

    return (
        <div className="App">
            <ul>
                {channelList.map(item => {
                    return <li key={item.id}>{item.name}</li>
                })}
            </ul>
        </div>
    );
}

export default App;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
  1. 写好store
    1. 先定义好同步修改的操作
    2. 再定义异步获取的部分
  2. 再根里面进行结合
  3. 使用中间件react-redux连接
  4. 注入store
  5. 触发action执行
    1. useDispatch
    2. actionCreater导入进来
    3. useEffect
  6. 获取渲染数据列表
    1. useSelector
    2. 渲染

# 基本例子

  1. 安装

    yarn add @reduxjs/toolkit react-redux

  2. 创建src/store/reducers/count.ts和src/store/index.js

  3. 在count中

    import { createSlice } from "@reduxjs/toolkit";
    
    export const countSlice = createSlice({
      name: "count",
      initialState: {
        value: 0
      },
      reducers: {
        increment: (state) => {
          state.value += 1;
        },
        decrement: (state) => {
          state.value -= 1;
        }
      }
    });
    
    export const { increment, decrement } = countSlice.actions;
    
    export default countSlice.reducer;
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
  4. 在index.js

    import { configureStore } from "@reduxjs/toolkit";
    import countReducer from "./reducers/count";
    
    export default configureStore({
      reducer: {
        count: countReducer,
      },
    });
    
    1
    2
    3
    4
    5
    6
    7
    8
  5. 在./index.js

    /**
     * @format
     */
    
    import { AppRegistry } from "react-native";
    import App from "./App";
    import { name as appName } from "./app.json";
    
    import { Provider } from "react-redux";
    import store from "./src/store";
    
    const ProviderApp = () => (<Provider store={store}>
        <App />
      </Provider>);
    
    AppRegistry.registerComponent(appName, () => ProviderApp);
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
  6. 在App

    <Provider store={store}>
      <Routes />
    </Provider>
    
    1
    2
    3
上次更新: 2024/08/14, 04:14:33
React权限控制
json-server

← React权限控制 json-server→

最近更新
01
React Native 使用SVG
08-13
02
Docker基础命令
08-04
03
算数逻辑单元
07-30
更多文章>
Theme by Vdoing | Copyright © 2021-2024 WeiXiaojing | 友情链接
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式