React笔记(九)RTK

一、RTK的简介

1、官网地址

Redux Toolkit: 概览 | Redux 中文官网

2、Redux toolkit是什么

Redux Toolkit 是 Redux 官方强烈推荐,开箱即用的一个高效的 Redux 开发工具集。它旨在成为标准的 Redux 逻辑开发模式,我们强烈建议你使用它。

它包括几个实用程序功能,这些功能可以简化最常见场景下的 Redux 开发,包括配置 store、定义 reducer,不可变的更新逻辑、甚至可以立即创建整个状态的 "切片 slice",而无需手动编写任何 action creator 或者 action type。它还自带了一些最常用的 Redux 插件,例如用于异步逻辑 Redux Thunk,用于编写选择器 selector 的函数 Reselect ,你都可以立刻使用。

二、RTK入门使用

1、安装依赖

javascript 复制代码
yarn add react-redux
yarn add @reduxjs/toolkit

2、目录结构

javascript 复制代码
|-src
    |-store
        |-modules
            |-shopcartList.js
            |-counter.js
        |-index.js

3、创建slice切片

位置:src/store/modules/counter.js

javascript 复制代码
import {createSlice} from '@reduxjs/toolkit'
const counter=createSlice({
    //命名空间,name值会作为action type的前缀
    name:'counter',
    //初始化状态
    initialState:{
        count:0
    },
    //定义reducer更新状态的函数
    reducers:{
        increment(state,action){
            state.count=state.count+action.payload
        },
        subtraction(state,action){
            state.count=state.count-action.payload
        }
    }
})
//导出action函数
export const {increment,subtraction}=counter.actions
//导出reducer
export default counter.reducer

4、创建store

位置:src/store/index.js

javascript 复制代码
import {configureStore} from '@reduxjs/toolkit'
import counter from './modules/counter'
const store=configureStore({
  reducer:{
    counter
  }  
})
export default store

5、在入口集成redux

javascript 复制代码
import {Provider} from 'react-redux'
import store from './store';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <Provider store={store}>
        <App></App>
    </Provider>
);

6、在组件中获取和更新状态

javascript 复制代码
import React from 'react'
import {useSelector,useDispatch} from 'react-redux'
import {increment} from '../store/modules/counter'
export default function Counter() {
  const num=useSelector((state)=>{
    console.log('state',state);
    return state.counter.count
  })
  const dispatch=useDispatch()
  const add=(n)=>{
    dispatch(increment(n))
  }
  return (
    <div>
      <h1>计数器</h1>
      <div>{num}</div>
      <button onClick={()=>{add(2)}}>+</button>
    </div>
  )
}

三、RTK异步操作

  • 编写异步方法

位置:src/store/modules/counter.js

javascript 复制代码
export const subtractionAsync=(payload)=>{
    return async(dispatch,getState)=>{
        console.log('dipatch',dispatch);
        console.log('getState',getState());
        setTimeout(() => {
            dispatch(subtraction(payload))
        }, 4000);
    }
}
  • 在组件中调用
javascript 复制代码
import React from 'react'
import {useSelector,useDispatch} from 'react-redux'
import {subtractionAsync} from '../store/modules/counter'
export default function Counter() {
  const num=useSelector((state)=>{
    return state.counter.count
  })
  const dispatch=useDispatch()
  const jian=(n)=>{
    dispatch(subtractionAsync(n))
  }
  return (
    <div>
      <h1>计数器</h1>
      <div>{num}</div>
      <button onClick={()=>{jian(3)}}>异步-</button>
    </div>
  )
}
相关推荐
Dream-Y.ocean4 小时前
鸿蒙PC平台宅匠 3D 室内设计适配实战:基于 Electron 壳方案的 Three.js 双渲染引擎与参数化户型编辑器开发
javascript·3d·harmonyos
Highcharts.js5 小时前
Highcharts Gantt使用符号的自定义数据标签开发甘特图示例
javascript·甘特图·highcharts·图表开发·实战代码·响应式图表
前进的李工6 小时前
Agent 学习笔记 05:系统提示词应该怎么写
笔记·学习·prompt·agent·个人开发·few-shot·ai应用开发
JavaPub-rodert7 小时前
从零搭建通用管理后台:ShiyuAdmin 的 Go、React 与 RBAC 实践
开发语言·react.js·golang
蒸蒸yyyyzwd8 小时前
后端学习笔记三个知识
笔记·八股
kyriewen8 小时前
Skills 榜前 10 我全装了:只有 3 个能直接用
前端·javascript·程序员
工控丫丫9 小时前
帆软看板中经常使用的公式函数及经常搭的组合
前端·javascript·数据库
Zhao-Jichao10 小时前
AI Prompting for Everyone 课程笔记 - P19 数据分析 Data Analysis
人工智能·笔记·数据分析
旖旎夜光10 小时前
【C++ 基础入门】类和对象(上):封装、对象模型与 this 指针
开发语言·c++·笔记·学习
ACP广源盛1392462567311 小时前
选型笔记:Type‑C 扩展坞方案评估|DP1.2 转 HDMI2.0 桥接芯片 GSV2201D@ACP
笔记·硬件架构·硬件工程·视频·国产芯片