Redux的基本使用详解(幼儿园难度,有手就行)

Redux的基本使用过程详解

学习文档

中文文档: http://www.redux.org.cn/
英文文档: https://redux.js.org/
Github: https://github.com/reactjs/redux

一,redux是什么

1,介紹:

  1. redux是一个专门用于做状态管理的JS库(不是react插件库)
  2. 它可以用在react, angular, vue等项目中, 但基本与react配合使用
  3. 作用: 集中式管理react应用中多个组件共享的状态

2,什么情况下需要使用redux

  1. 某个组件的状态,需要让其他组件可以随时拿到(共享)
  2. 一个组件需要改变另一个组件的状态(通信)。
  3. 总体原则:能不用就不用, 如果不用比较吃力才考虑使用

3, redux工作流程

在这里插入图片描述

二,redux的三个核心概念

1,action

  1. 动作的对象
  2. 包含2个属性
    type:标识属性, 值为字符串, 唯一, 必要属性
    data:数据属性, 值类型任意, 可选属性
  3. 例子:{ type: ‘ADD_STUDENT’,data:{name: ‘tom’,age:18} }

2,reducer

  1. 用于初始化状态、加工状态。
  2. 加工时,根据旧的state和action, 产生新的state的纯函数。

3,store

  1. 将state、action、reducer联系在一起的对象
  2. 如何得到此对象?
import {
    
    createStore} from 'redux'
import reducer from './reducers'
const store = createStore(reducer)
  1. 此对象的功能?
    getState(): 得到state
    dispatch(action): 分发action, 触发reducer调用, 产生新的state
    subscribe(listener): 注册监听, 当产生了新的state时, 自动调用

三,redux的核心API

1,createstore()

作用:创建包含指定reducer的store对象

2,store对象

  1. 作用: redux库最核心的管理对象
  2. 它内部维护着:

state
reducer

  1. 核心方法:

getState()
dispatch(action)
subscribe(listener)

  1. 具体编码:

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

3,applyMiddleware()

作用:应用上基于redux的中间件(插件库)

4,combineReducers()

作用:合并多个reducer函数

四,使用redux编写应用

1,安装

npm install --save redux

2,新建文件

src路径下,新建store文件

在这里插入图片描述

3,定义仓库:

新建src / store / index.js

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

4,创建计数器数据,及修改数据的方法:

新建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, 在组件中使用 redux

src / views/ ProductView.js 文件:


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;

效果图:

在这里插入图片描述

五,redux异步编程

1,理解:

  1. redux默认是不能进行异步处理的,
  2. 某些时候应用中需要在redux中执行异步任务(ajax, 定时器)

2,使用异步中间件

npm install --save redux-thunk

六,react-redux

1, 理解

  1. 一个react插件库
  2. 专门用来简化react应用中使用redux

2,react-Redux将所有组件分成两大类

  1. UI组件
  1. 只负责 UI 的呈现,不带有任何业务逻辑
  2. 通过props接收数据(一般数据和函数)
  3. 不使用任何 Redux 的 API
  4. 一般保存在components文件夹下
  1. 容器组件
  1. 负责管理数据和业务逻辑,不负责UI的呈现
  2. 使用 Redux 的 API
  3. 一般保存在containers文件夹下

3,相关API

  1. Provider:让所有组件都可以得到state数据
<Provider store={
    
    store}>
  <App />
</Provider>

  1. connect:用于包装 UI 组件生成容器组件
import {
    
     connect } from 'react-redux'
  connect(
    mapStateToprops,
    mapDispatchToProps
  )(Counter)

  1. mapStateToprops:将外部的数据(即state对象)转换为UI组件的标签属性
const mapStateToprops = function (state) {
    
    
  return {
    
    
    value: state
  }
}

  1. mapDispatchToProps:将分发action的函数转换为UI组件的标签属性

七,使用上redux调试工具

1,安装chrome浏览器插件

在这里插入图片描述

2, 下载工具依赖包

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

八,纯函数和高阶函数

1,纯函数

  1. 一类特别的函数: 只要是同样的输入(实参),必定得到同样的输出(返回)
  2. 必须遵守以下一些约束
  1. 不得改写参数数据
  2. 不会产生任何副作用,例如网络请求,输入和输出设备
  3. 不能调用Date.now()或者Math.random()等不纯的方法
  1. redux的reducer函数必须是一个纯函数

2,高阶函数

  1. 理解: 一类特别的函数

    1. 情况1: 参数是函数
    2. 情况2: 返回是函数
  2. 常见的高阶函数:

    1. 定时器设置函数
    2. 数组的forEach()/map()/filter()/reduce()/find()/bind()
    3. promise
    4. react-redux中的connect函数
  3. 作用: 能实现更加动态, 更加可扩展的功能

    请添加图片描述

猜你喜欢

转载自blog.csdn.net/m0_64875238/article/details/130029878
今日推荐