2026-06-29 22:20:32
Redux 是一个用于 JavaScript 应用程序的状态管理库,它可以帮助你管理应用程序的全局状态。以下是 Redux 的核心概念和基本使用方法的详细说明:
Redux 的核心概念Store:
Redux 为整个项目提供一个唯一的 store,它是应用程序状态的单一来源。
你可以使用 store.dispatch(action) 的方式去修改 store 中的数据。
Store 集成了 dispatch、getState、subscribe、replaceReducer 四个方法。
import { createStore } from "redux";const store = createStore(reducer, preloadState, enhancer);// createStore 的第一个参数是 reducerexport default store;State is Read-Only:
在 Redux 中,state 是只读的,类似于 React 中的 state,不能直接改变。
要修改 state,必须使用 dispatch(action) 方法。
Changes are Made with Pure Functions:
Reducer 是一个纯函数,它接收先前的 state 和一个 action,然后返回一个新的 state。
纯函数没有副作用,对于相同的输入总是产生相同的输出,这使得它们更易于测试和预测。
Action 是一个对象,通常包含一个 type 字段,用于描述发生了什么。
可以使用 action creator 函数来生成 action。
let action = { type: "add", value: 2};const addState = (value) => ({ type: "add", value});// 使用 dispatch 方法import store from "store";store.dispatch(addState(1));Reducer 是一个纯函数,根据 action 的类型来更新 state。
对于复杂的应用,可以将 reducer 拆分为多个小的 reducer,然后使用 combineReducers 合并。
const reducer = (preState = {}, action) => { switch (action.type) { case "add": return { ...preState, number: preState.number + action.value }; case "sub": return { ...preState, number: preState.number - action.value }; default: return preState; }};// 拆分 reducerimport { combineReducers } from "redux";const finalReducer = combineReducers({ data1: reducer1, data2: reducer2,});以下是一个简单的 createStore 和 combineReducers 的实现:
function createStore(reducer, preloadState, enhancer) { let currentState = preloadState; let currentReducer = reducer; let currentListeners = []; const getState = () => currentState; const dispatch = (action) => { if (!isPlainObject(action)) { throw new Error("Action must be plain objects."); } if (typeof action.type === "undefined") { throw new Error("Action must have type property"); } currentState = currentReducer(currentState, action); currentListeners.forEach(listener => listener()); }; const subscribe = (listener) => { if (typeof listener !== "function") { throw new Error("Expected the listener to be a function."); } currentListeners.push(listener); return function unsubscribe() { const index = currentListeners.indexOf(listener); currentListeners.splice(index, 1); }; }; const replaceReducer = (newReducer) => { currentReducer = newReducer; }; return { dispatch, getState, subscribe, replaceReducer };}function combineReducers(reducers) { return (state = {}, action) => { return Object.keys(reducers).reduce((nextState, key) => { nextState[key] = reducers[key](state[key], action); return nextState; }, {}); };}总结Redux 通过提供一个集中的 store 来管理应用程序的状态,使用 action 来描述状态的变化,并通过纯函数 reducer 来处理这些变化。通过这种方式,Redux 提供了一种可预测的状态管理机制,使得大型复杂应用的状态管理更加清晰和可维护。