文章目录
开发公司工具包的使用
Redux 介绍
Redux Toolkit 开发公司是官方推荐的编写 Redux 开发公司逻辑的方法。
开发公司在前面我们学习Redux开发公司的时候应该已经发现,redux开发公司的编写逻辑过于的繁琐和麻烦。
开发公司并且代码通常分拆在多个文件中(虽然也可以放到一个文件管理,但是代码量过多,不利于管理);
Redux Toolkit包旨在成为编写Redux逻辑的标准方式,从而解决上面提到的问题;
在很多地方为了称呼方便,也将之称为“RTK”;
安装Redux Toolkit:npm install @reduxjs/toolkit react-redux
Redux Toolkit的核心API主要是如下几个:
configureStore
: 包装createStore以提供简化的配置选项和良好的默认值。它可以自动组合你的 slice reducer,添加你提供 的任何 Redux 中间件,redux-thunk默认包含,并启用 Redux DevTools Extension。
createSlice
: 接受reducer函数的对象、切片名称和初始状态值,并自动生成切片reducer,并带有相应的actions。
createAsyncThunk
: 接受一个动作类型字符串和一个返回承诺的函数,并生成一个pending/fulfilled/rejected基于该承诺分 派动作类型的 thunk
Redux Toolkit基本使用
configureStore
用于创建store对象,常见参数如下:
reducer: 将slice中的reducer可以组成一个对象传入此处;
middleware:可以使用参数,传入其他的中间件(自行了解);
devTools:是否配置devTools工具,默认为true;
import { configureStore } from "@reduxjs/toolkit"// 导入reducerimport counterReducer from "./features/counter"const store = configureStore({ reducer: { counter: counterReducer }, // 例如可以关闭redux-devtool devTools: false})export default store
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
createSlice
主要包含如下几个参数:
name:用户标记slice的名词
在之后的redux-devtool中会显示对应的名词;
initialState:初始化值
第一次初始化时的值;
reducers:相当于之前的reducer函数
对象类型,对象中可以添加很多的函数;
函数类似于redux原来reducer中的一个case语句;
函数的参数:
- 参数一: state, 当前的state状态
- 参数二: 传递的actions参数, actions有两个属性, 一个是自动生成的type, 另一个是传递的参数放在payload中;
createSlice返回值是一个对象,包含所有的actions;
import { createSlice } from "@reduxjs/toolkit"const counterSlice = createSlice({ name: "counter", initialState: { counter: 99 }, reducers: { // 直接对actions解构拿到payload changeNumber(state, { payload }) { state.counter = state.counter + payload } }})// reducers当中的方法会放在counterSlice的actions中, 用于派发actionexport const { changeNumber } = counterSlice.actions// 注意: 导出的是reducer, 用于在index.js中对reducer进行组合export default counterSlice.reducer
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
接下来使用store中的counter数据和修改counter的操作和之前一样, 借助于react-redux库进行连接使用
import React, { PureComponent } from 'react'import { connect } from 'react-redux'import { changeNumber } from '../store/features/counter'export class Home extends PureComponent { changeNumber(num) { this.props.changeNumber(num) } render() { const { counter } = this.props return ( <div> <h2>Home</h2> <h2>当前计数: {counter}</h2> <button onClick={() => this.changeNumber(5)}>+5</button> <button onClick={() => this.changeNumber(10)}>+10</button> </div> ) }}// 映射要使用的store中的数据const mapStateToProps = (state) => ({ counter: state.counter.counter})// 映射要派发的方法const mapDispatchToProps = (dispatch) => ({ changeNumber(num) { dispatch(changeNumber(num)) }})export default connect(mapStateToProps, mapDispatchToProps)(Home)
- 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