Yasin

Yasin

什么是Redux

Redux 是什么

Redux 是一个状态管理库,用于集中管理应用中的全局状态。

核心思想:把所有状态放在一个全局 Store 里,组件从 Store 读取数据,通过 Action 修改数据。


为什么需要 Redux

没有 Redux 时,组件间共享状态需要:

  • 层层 props 传递(prop drilling)
  • 或者用 Context

当状态复杂、组件层级深时,这些方案维护困难。


核心概念

Store(仓库)

整个应用只有一个 Store,存放所有全局状态:

const store = createStore(reducer);

Action(动作)

描述"发生了什么"的普通对象:

const action = {
  type: "INCREMENT",
  payload: 1,
};

Reducer(处理器)

接收旧 state 和 action,返回新 state:

function counterReducer(state = { count: 0 }, action) {
  switch (action.type) {
    case "INCREMENT":
      return { count: state.count + action.payload };
    case "DECREMENT":
      return { count: state.count - action.payload };
    default:
      return state;
  }
}

Dispatch(派发)

触发 Action 的唯一方式:

store.dispatch({ type: "INCREMENT", payload: 1 });

数据流

用户操作
dispatch(action)
Reducer 计算新 state
Store 更新
组件重新渲染

单向数据流,状态变化可预测、可追踪。


在 React 中使用(Redux Toolkit 现代写法)

现在推荐用 Redux Toolkit(RTK),不再手写繁琐的 action/reducer。

安装

npm install @reduxjs/toolkit react-redux

创建 Slice

// store/counterSlice.ts
import { createSlice } from "@reduxjs/toolkit";

const counterSlice = createSlice({
  name: "counter",
  initialState: { count: 0 },
  reducers: {
    increment(state) {
      state.count += 1; // RTK 内部用 immer,可以直接"修改"
    },
    decrement(state) {
      state.count -= 1;
    },
    incrementBy(state, action) {
      state.count += action.payload;
    },
  },
});

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

创建 Store

// store/index.ts
import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./counterSlice";

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

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

注入 Provider

// main.tsx
import { Provider } from "react-redux";
import { store } from "./store";

ReactDOM.createRoot(document.getElementById("root")!).render(
  <Provider store={store}>
    <App />
  </Provider>,
);

组件中使用

import { useSelector, useDispatch } from "react-redux";
import { increment, decrement } from "./store/counterSlice";
import type { RootState } from "./store";

export default function Counter() {
  const count = useSelector((state: RootState) => state.counter.count);
  const dispatch = useDispatch();

  return (
    <div>
      <p>{count}</p>
      <button onClick={() => dispatch(increment())}>+1</button>
      <button onClick={() => dispatch(decrement())}>-1</button>
    </div>
  );
}

Redux vs Context

Redux Context
适合场景 复杂全局状态 少量全局数据
性能优化 内置精准订阅 需手动优化
调试工具 Redux DevTools
学习成本 较高
异步处理 RTK Query / thunk 需自己处理

现在还用 Redux 吗

  • 中大型项目:仍然常用,尤其配合 RTK
  • 小项目Context + useState 足够
  • 新竞品Zustand(更轻量)、JotaiRecoil 也很流行