Redux - 核心概念
Redux - 核心概念
Section titled “Redux - 核心概念”Redux 围绕着几个核心概念,这些概念确保了 JavaScript 应用中可预测的 State 管理。理解这些概念是有效使用 Redux 的关键。
1. 单一数据源 (Store)
Section titled “1. 单一数据源 (Store)”应用的整个 State 存储在单个 Store 中的一个 JavaScript 对象里。这使得追踪变更、调试问题以及实现状态持久化或服务端渲染等功能变得更加容易。State 不再分散在各种 Component 中,而是有一个集中的位置。
示例 State 结构:
{ // State managed by itemsSlice items: { list: [], status: 'idle', error: null }, // State managed by authSlice auth: { user: null, token: null }, // Other parts of the state...}2. State 是只读的 (Actions)
Section titled “2. State 是只读的 (Actions)”改变 State 的唯一方法是 Dispatch 一个 Action。Action 是描述发生了什么的普通 JavaScript 对象。它们必须有一个 type 属性(通常是一个字符串常量),指示正在执行的 Action 类型。它们可以选择携带一个包含状态变更所需数据的 payload。
虽然您可以手动创建 Action,但 Redux Toolkit 的 createSlice 会自动生成 Action Creator。这些是返回 Action 对象的函数。
// Example action object (conceptually){ type: 'counter/increment', // Format often used by createSlice: 'sliceName/reducerName'}
// Another example with payload{ type: 'items/itemAdded', payload: { id: 1, name: 'New Item' } // Data associated with the action}
// Using an action creator generated by createSliceimport { increment } from './features/counter/counterSlice';dispatch(increment()); // Dispatches { type: 'counter/increment' }
import { itemAdded } from './features/items/itemsSlice';dispatch(itemAdded({ id: 1, name: 'New Item' })); // Dispatches { type: 'items/itemAdded', payload: { ... } }Dispatch 一个 Action 并不会直接改变 State;它只是发出一个意图改变 State 的信号。
3. 使用纯函数进行变更 (Reducers)
Section titled “3. 使用纯函数进行变更 (Reducers)”为了指定 State 树如何通过 Action 进行转换,您需要编写纯 Reducer。Reducer 是一个函数,它接受先前的 state 和一个 action,并返回下一个 state。即 (previousState, action) => newState。
Reducer 必须是纯函数:它们不应该修改原始 State,不应执行副作用(如 API 调用),也不应依赖外部变量。给定相同的输入,它们必须始终产生相同的输出。
Redux Toolkit 的 createSlice 通过一个对象以更组织化的方式帮助定义 Reducer,该对象的键对应 Action 类型(隐式),值是针对这些 Action 的 Reducer 函数。它内部使用 Immer 来简化不可变更新逻辑的编写。
// Inside createSlice's 'reducers' option:
reducers: { increment: (state) => { // Immer handles immutability: this looks like mutation, // but produces a new state object. state.value += 1; }, itemAdded: (state, action) => { // action.payload contains the data for the new item state.list.push(action.payload); }}Redux 应用(尤其是与 React 结合使用时)的典型数据流是单向的:
- UI 事件: UI 中发生某事(例如,按钮点击)。
- Dispatch Action: 调用 Action Creator,然后使用
dispatch(action)Dispatch 生成的 Action。这通常通过 React Redux 的useDispatchhook 完成。 - Reducer 执行: Redux Store 使用当前 State 和 Dispatch 的 Action 运行根 Reducer 函数。相应的 Slice Reducer 处理该 Action。
- State 更新: Reducer 返回新的 State 对象。Store 保存这个新的 State。
- UI 更新: Store 通知 UI(例如,通过
useSelector连接的 React Component)State 已更改。读取受影响 State 部分的 Component 会用新数据重新渲染。
这种可预测的单向数据流使应用更容易理解、调试和维护。