Skip to content

Redux 速查表

可预测状态的 JavaScript 应用状态容器。

01

快速上手

Reducer

Reducer 是纯函数:(state, action) => state。

redux
function counter(state = 0, action) {
  switch (action.type) {
    case "INCREMENT": return state + 1;
    case "DECREMENT": return state - 1;
    default: return state;
  }
}

Store

Store 保存状态;用 dispatch 触发变更。

redux
import { createStore } from "redux";
const store = createStore(counter);

store.dispatch({ type: "INCREMENT" });
console.log(store.getState());

Redux Toolkit

Redux Toolkit 用 createSlice 简化 Redux。

redux
import { createSlice, configureStore } from "@reduxjs/toolkit";

const counter = createSlice({
  name: "counter",
  initialState: 0,
  reducers: {
    increment: s => s + 1,
    decrement: s => s - 1,
  }
});

const store = configureStore({ reducer: counter.reducer });
02

React 集成

useSelector

用于读取状态和分发 action 的 Hooks。

redux
import { useSelector, useDispatch } from "react-redux";

function Counter() {
  const count = useSelector(s => s);
  const dispatch = useDispatch();
  return <button onClick={() => dispatch({type: "INCREMENT"})}>{count}</button>;
}

这篇内容对您有帮助吗?