Redux Toolkit 快速入门指南:createSlice、configureStore、useSelector、useDispatch 全面解析

发布于:2025-06-10 ⋅ 阅读:(19) ⋅ 点赞:(0)


🚀 Redux Toolkit 快速入门指南:createSlice、configureStore、useSelector、useDispatch 全面解析

Redux 是管理 React 应用状态的主流方案,但传统 Redux 写法冗长、复杂,对初学者不友好。Redux 官方推出的 Redux Toolkit (RTK) 旨在解决这个问题,极大简化了 Redux 的配置和使用。

本文将带你快速掌握 Redux Toolkit 的四个核心工具:

  • createSlice:定义状态和修改逻辑
  • configureStore:创建 Redux store
  • useSelector:读取状态
  • useDispatch:修改状态

🧱 1. createSlice:定义状态和 reducer

createSlice 是 Redux Toolkit 的核心 API,用于简洁地定义:

  • 状态的初始值(initialState
  • 修改状态的函数(reducers
  • 自动生成的 action 和 action types
// features/counter/counterSlice.js
import { createSlice } from '@reduxjs/toolkit';

const counterSlice = createSlice({
  name: 'counter', // 模块名
  initialState: { value: 0 }, // 初始状态
  reducers: {
    increment: (state) => {
      state.value += 1; // 直接修改 state,RTK 内部用 Immer 自动处理
    },
    decrement: (state) => {
      state.value -= 1;
    },
    incrementByAmount: (state, action) => {
      state.value += action.payload;
    },
  },
});

export const { increment, decrement, incrementByAmount } = counterSlice.actions;
export default counterSlice.reducer;

🏗️ 2. configureStore:创建 Store 并整合多个 Slice

Redux Toolkit 提供了 configureStore 来创建 store。相比传统 Redux 的 createStore,它自动集成了:

  • Redux DevTools
  • redux-thunk 中间件(支持异步)
  • 默认的中间件安全校验
// app/store.js
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from '../features/counter/counterSlice';

export const store = configureStore({
  reducer: {
    counter: counterReducer, // 注册 reducer
  },
});

如果有多个 slice,只需继续添加即可,RTK 会自动组合成根 reducer。


🔍 3. useSelector:从 Redux 中读取状态

useSelector 是 React-Redux 提供的 Hook,用于从 Redux 中“选择”你关心的 state。

import { useSelector } from 'react-redux';

const count = useSelector((state) => state.counter.value);

✅ 特点:

  • 只要 state.counter.value 改变,组件才会重新渲染
  • 推荐只选择“需要的部分”,避免返回新对象(影响性能)

🧩 4. useDispatch:派发 action 修改状态

通过 useDispatch 获取 Redux 的 dispatch() 函数,在组件中触发状态更新。

import { useDispatch } from 'react-redux';
import { increment } from './counterSlice';

const dispatch = useDispatch();
dispatch(increment());

RTK 的 createSlice 自动生成了 increment() 这样的 action creator,使得 dispatch(increment()) 写法非常简洁。

也支持派发异步操作:

dispatch(fetchDataAsync());

💡 综合示例

一个最小可运行的 React + Redux Toolkit 示例:

// Counter.jsx
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement, incrementByAmount } from './features/counter/counterSlice';

function Counter() {
  const count = useSelector((state) => state.counter.value);
  const dispatch = useDispatch();

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => dispatch(increment())}>+1</button>
      <button onClick={() => dispatch(decrement())}>-1</button>
      <button onClick={() => dispatch(incrementByAmount(5))}>+5</button>
    </div>
  );
}

export default Counter;

🧠 总结一张图

Redux Toolkit 架构流程:

createSlice ➜ 自动生成 reducer + actions
         |
         ▼
configureStore ➜ 注册 reducer,创建 store
         |
         ▼
<Provider store={...}> ➜ 将 store 注入 React 应用
         |
         ▼
组件中使用:
- useSelector() 读取 state
- useDispatch() 派发 action

✅ 推荐理由:为什么选择 Redux Toolkit?

特性 优势
简洁 省去手写 action 类型、reducer、action creator 的繁琐过程
安全 默认开启状态修改保护和序列化检测
易学 API 更贴近 React Hooks 风格
内置中间件 自动支持异步操作,无需额外配置 thunk
DevTools 开箱即用,无需单独配置