Redux 状态管理流程是什么?
介绍 Redux 的状态管理流程,包括组件触发 Action、Reducer 处理状态变更、Store 更新状态以及组件响应更新。
Redux 状态管理流程围绕 单向数据流 设计,核心步骤如下:
1. 组件触发 Action
- 组件通过
dispatch
发起一个 Action(描述操作的普通 JavaScript 对象)。 - Action 必须包含
type
属性(唯一标识操作),可携带额外数据(如payload
)。
// 示例:定义一个同步 Action
const incrementAction = { type: "INCREMENT", payload: 1 };
// 组件中触发
dispatch(incrementAction);
2. Reducer 处理状态变更
- Action 会被传递给 Reducer(纯函数),根据当前状态和 Action 类型生成新状态。
- Reducer 必须保持不可变更新,直接返回新对象而非修改原状态。
const initialState = { count: 0 };
function counterReducer(state = initialState, action) {
switch (action.type) {
case "INCREMENT":
return { ...state, count: state.count + action.payload }; // 返回新对象
default:
return state;
}
}
3. Store 更新状态
- Redux Store(单一全局状态树)调用 Reducer 后更新状态,并通知所有订阅者。
import { createStore } from "redux";
const store = createStore(counterReducer); // 绑定 Reducer 创建 Store
4. 组件响应更新
- 使用
connect
或 Hooks(如useSelector
)连接 Store 的组件会自动重新渲染,获取新状态并更新 UI。
// 使用 React-Redux 的 connect
import { connect } from "react-redux";
const mapStateToProps = (state) => ({ count: state.count });
export default connect(mapStateToProps)(CounterComponent);
⚡ 异步流程扩展
处理异步操作时需引入中间件(Middleware)(如 redux-thunk
或 redux-saga
):
- 创建异步 Action:Action 可返回函数而非对象(
thunk
允许内部执行异步任务)。 - 中间件拦截:中间件在
dispatch
和reducer
之间拦截 Action,执行异步操作后再派发结果。
// 异步 Action(使用 redux-thunk)
const fetchData = () => (dispatch) => {
axios.get("/api/data")
.then((res) => dispatch({ type: "FETCH_SUCCESS", payload: res.data }));
};
📝 关键原则
- 单一数据源:应用状态全局存储在唯一 Store。
- 状态只读:仅能通过
dispatch(action)
更新。 - 纯函数更新:Reducer 必须无副作用,确保状态变更可预测。