列出 Redux 的组件?

在 Redux 中,“组件”通常指的是它的核心构成部分(即实现状态管理的几个关键模块),而不是 React 里的 UI 组件。Redux 体系主要由以下 5 大核心部分 组成

Redux 的核心组件

组件 作用 说明
Store 存储数据的地方 整个应用只有一个 Store,负责保存所有状态。
Action 描述“发生了什么” 是一个普通对象,必须包含一个 type 字段(事件类型)。
Reducer 处理状态变化的纯函数 根据不同的 Action,返回新的 state。
Dispatch 分发 Action 的方法 触发状态更新的唯一方式,store.dispatch(action)
Subscriber(订阅者) 监听 state 的变化 当 state 改变时,执行回调函数,比如刷新 UI。

数据流动示意(单向数据流)

UI 组件 → dispatch(action)
           ↓
        Reducer(state, action)
           ↓
        Store 更新 state
           ↓
     UI 组件通过订阅获取新 state

React + Redux 常用辅助组件(结合使用)

当 Redux 和 React 一起用时,还会接触到以下“辅助组件/库”:

组件 / 函数 来自 作用
Provider react-redux 用于把 Redux store 注入整个 React 组件树
connect react-redux 高阶组件,用于连接 React 组件与 Redux store
useSelector react-redux React hook,用于在函数组件中读取 state
useDispatch react-redux React hook,用于在函数组件中分发 action
createStore redux 创建 Store
combineReducers redux 合并多个 reducer
applyMiddleware redux 添加中间件(如 redux-thunkredux-saga

示例代码

// 1️⃣ 定义 action
const increment = () => ({ type: 'INCREMENT' });

// 2️⃣ 定义 reducer
function counter(state = 0, action) {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    default:
      return state;
  }
}

// 3️⃣ 创建 store
import { createStore } from 'redux';
const store = createStore(counter);

// 4️⃣ 订阅变化
store.subscribe(() => console.log(store.getState()));

// 5️⃣ 分发 action
store.dispatch(increment());
posted @ 2025-10-21 09:24  煜火  阅读(7)  评论(0)    收藏  举报