
redux toolkit 是官方推荐的编写 redux 逻辑的方法。它为开箱即用的商店设置提供了良好的默认设置,并包含最常用的内置 redux 插件。在本博客中,我们将介绍将 redux toolkit 与 react 应用程序集成的基础知识。
什么是 redux 工具包?
redux toolkit 是一组有助于简化编写 redux 逻辑过程的工具。它包括用于简化常见用例的实用程序,例如存储设置、创建减速器和编写不可变的更新逻辑。
使用 react 设置 redux 工具包
让我们完成在 react 应用程序中设置 redux toolkit 的步骤。
第 1 步:安装依赖项
首先,您需要安装必要的软件包。您可以使用 npm 或yarn 来完成此操作。
| 1 | 
npm install @reduxJS/toolkit react-redux
 | 
 
第 2 步:创建 redux store
store 是赋予 redux 生命的对象。借助 redux toolkit,您可以使用 configurestore 函数创建商店。
| 1 2 3 4 5 6 7 8 9 10 11 | 
import { configurestore } from '@reduxjs/toolkit';
 import counterreducer from './features/counter/counterslice';
 
 conststore = configurestore({
   reducer: {
     counter: counterreducer,
   },
 });
 
 export defaultstore;
 | 
 
第 3 步:创建切片
切片是应用程序单个功能的 redux 减速器逻辑和操作的集合。 redux toolkit 的 createslice 函数会自动生成动作创建者和动作类型。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 
import { createslice } from '@reduxjs/toolkit';
 
 constcounterslice = createslice({
   name: 'counter',
   initialstate: {
     value: 0,
   },
   reducers: {
     increment: (state) => {
       state.value += 1;
     },
     decrement: (state) => {
       state.value -= 1;
     },
   },
 });
 
 export const{ increment, decrement } = counterslice.actions;
 
 export defaultcounterslice.reducer;
 | 
 
第 4 步:为您的 react 应用程序提供 store
要使 redux 存储可供您的 react 组件使用,您需要使用 react-redux 中的 provider 组件。
| 1 2 3 4 5 6 7 8 9 10 11 | 
import react from 'react';
 import reactdom from 'react-dom';
 import { provider } from 'react-redux';
 import app from './app';
 import store from './store';
 
 reactdom.render(
   <provider store="{store}"><app></app></provider>,
   document.getelementbyid('root')
 );
 | 
 
第 5 步:将 react 组件连接到 redux store
要将 react 组件连接到 redux 存储,您可以使用react-redux 中的 useselector 和 usedispatch 钩子。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 
import { useselector, usedispatch } from 'react-redux';
 import { increment, decrement } from '../features/counter/counterslice';
 
 functioncounter() {
   constcount= useselector((state) => state.counter.value);
   constdispatch = usedispatch();
 
   return(
     <div>
       <h1>{count}</h1>
       <button onclick="{()"> dispatch(increment())}>increment</button>
       <button onclick="{()"> dispatch(decrement())}>decrement</button>
     </div>
   );
 }
 
 export defaultcounter;
 | 
 
第 6 步:在您的应用程序中使用连接的组件
最后,您可以在应用程序中使用连接的组件。
| 1 2 3 4 5 6 7 8 9 10 11 12 | 
import Counter from './components/Counter';
 
 functionApp() {
   return(
     <div>
       <counter></counter>
 </div>
   );
 }
 
 export defaultApp;
 | 
 
结论
通过执行以下步骤,您可以在 react 应用程序中设置 redux toolkit,以可预测和可维护的方式管理状态。 redux toolkit 简化了使用 redux 时的许多常见任务,使编写和维护 redux 逻辑变得更加容易。
进一步探索
对于那些想要深入了解 redux toolkit 和 react 的人,这里有一些宝贵的资源:
- redux toolkit 文档:官方文档提供了全面的指南和 API 参考。
- react redux 文档:了解有关如何将 redux 与 react 结合使用的更多信息。
- redux essentials 教程:帮助您启动并运行 redux toolkit 的分步教程。
- redux 基础教程:涵盖 redux 核心概念的详细教程。