Redux - Store
Redux - Store
Section titled “Redux - Store”The Store is the heart of a Redux application. It’s a single JavaScript object that holds the complete state tree of your application. Think of it as the single source of truth for all your application data.
Store 是 Redux 应用的核心。它是一个 JavaScript 对象,包含应用完整的状态树 (state tree)。可以把它看作是应用所有数据的单一事实来源 (single source of truth)。
Key characteristics of the Redux store:
Redux store 的关键特性:
- Holds the application state.
- 保存应用状态。
- Allows access to the state via
getState(). - 通过
getState()访问状态。 - Allows state to be updated via
dispatch(action). - 通过
dispatch(action)更新状态。 - Registers listeners via
subscribe(listener). - 通过
subscribe(listener)注册监听器。 - Unregisters listeners via the function returned by
subscribe(listener). - 通过
subscribe(listener)返回的函数注销监听器。
Crucially, there should only be one store in a Redux application. Managing multiple stores would defeat the purpose of having a single, predictable state container.
至关重要的是,一个 Redux 应用中应该只有一个 store。管理多个 store 会违背拥有单一、可预测状态容器 (state container) 的目的。
Creating a Store with Redux Toolkit (Recommended)
Section titled “Creating a Store with Redux Toolkit (Recommended)”使用 Redux Toolkit 创建 Store(推荐)
Section titled “使用 Redux Toolkit 创建 Store(推荐)”The modern and recommended way to create a Redux store is using the configureStore function from @reduxjs/toolkit. It simplifies the setup process significantly.
现代且推荐创建 Redux store 的方式是使用 @reduxjs/toolkit 中的 configureStore 函数。它显著简化了设置过程。
import { configureStore } from '@reduxjs/toolkit';// Import your reducers (likely created with createSlice or combineReducers)import rootReducer from './reducers';
const store = configureStore({ reducer: rootReducer, // Pass the root reducer (or an object of slice reducers) // Middleware and DevTools are automatically configured!});
export default store;configureStore handles several things automatically:
configureStore 会自动处理几件事情:
- Combines your slice reducers (if you provide an object) into the root reducer.
- 将你的 slice reducer(如果你提供了一个对象)组合成根 reducer。
- Applies helpful middleware by default, including
redux-thunkfor async logic. - 默认应用有用的 middleware(中间件),包括用于异步逻辑 (async logic) 的
redux-thunk。 - Sets up the Redux DevTools Extension integration automatically (in development mode).
- 自动集成 Redux DevTools Extension(在开发模式下)。
You can optionally provide preloadedState (initial state) and customize middleware or enhancers if needed.
如果需要,你可以选择提供 preloadedState(初始状态),并定制 middleware 或 enhancers。
Creating a Store (Legacy createStore)
Section titled “Creating a Store (Legacy createStore)”创建 Store(旧版 createStore)
Section titled “创建 Store(旧版 createStore)”While configureStore is recommended, understanding the original createStore API helps grasp the fundamentals. (Note: createStore is now marked as @deprecated in favor of configureStore).
虽然推荐使用 configureStore,但理解原始的 createStore API 有助于掌握基本原理 (fundamentals)。(注意:createStore 现在已被标记为 @deprecated(已废弃),推荐使用 configureStore)。
import { createStore, applyMiddleware } from 'redux';import { thunk } from 'redux-thunk'; // 示例 middlewareimport rootReducer from './reducers';
const initialState = {}; // 可选的初始状态
// 基本 store// const store = createStore(rootReducer, initialState);
// 包含 middleware 的 storeconst store = createStore( rootReducer, initialState, applyMiddleware(thunk) // 显式应用 middleware);
export default store;The createStore function takes the root reducer as the first argument. Optional arguments include the preloadedState (initial state) and an enhancer (typically the result of applyMiddleware).
createStore 函数将根 reducer 作为第一个参数。可选参数包括 preloadedState(初始状态)和一个 enhancer(通常是 applyMiddleware 的结果)。
Store Methods
Section titled “Store Methods”Store 方法
Section titled “Store 方法”Once the store is created (using either method), you interact with it using these core methods:
store 创建后(使用任一方法),你可以使用这些核心方法与其交互 (interact):
getState()
Section titled “getState()”getState()
Section titled “getState()”Returns the current state tree of your application. It’s the only way to access the state directly.
返回应用的当前状态树。这是直接访问状态的唯一方式。
const currentState = store.getState();console.log('Current state:', currentState);dispatch(action)
Section titled “dispatch(action)”dispatch(action)
Section titled “dispatch(action)”This is the only way to trigger a state change. You pass an action object (or a function, if using Thunk middleware) to dispatch. Redux then calls your reducer with the current state and the action, updating the state based on the reducer’s logic.
这是触发状态改变 (state change) 的唯一方式。你向 dispatch 传递一个 action 对象(或者一个函数,如果使用了 Thunk middleware)。然后 Redux 会使用当前状态和 action 调用你的 reducer,根据 reducer 的逻辑更新状态。
// 派发一个普通 action 对象store.dispatch({ type: 'counter/increment' });
// 派发一个 thunk action(如果配置了 thunk middleware)// store.dispatch(fetchUserData());subscribe(listener)
Section titled “subscribe(listener)”subscribe(listener)
Section titled “subscribe(listener)”Registers a callback function (listener) that will be called every time an action is dispatched and the state might have changed. It’s commonly used to update the UI in response to state changes (though UI libraries like React Redux handle this automatically).
注册一个回调函数 (callback function)(listener),每当派发一个 action 且状态可能发生改变时,该函数就会被调用。它通常用于根据状态变化更新 UI(尽管像 React Redux 这样的 UI 库会自动处理这一点)。
The subscribe method returns a function that you can call to unsubscribe the listener.
subscribe 方法会返回一个函数,调用该函数可以注销监听器 (unsubscribe the listener)。
const handleChange = () => { console.log('State changed:', store.getState());};
const unsubscribe = store.subscribe(handleChange);
// 之后,要停止监听:unsubscribe();In typical applications using UI frameworks like React or Angular, you won’t call subscribe directly very often. Libraries like react-redux use the store’s subscription mechanism internally to connect your components to the Redux state and re-render them automatically when needed.
在典型的使用 React 或 Angular 等 UI 框架的应用中,你不会经常直接调用 subscribe。像 react-redux 这样的库会在内部使用 store 的订阅机制,将你的组件连接到 Redux 状态,并在需要时自动重新渲染 (re-render) 它们。