Skip to main content

存储

¥Store

存储保存你的应用的整个 状态树。改变其内部状态的唯一方法是在其上调度 action,这会触发 根减速函数 计算新状态。

¥A store holds the whole state tree of your application. The only way to change the state inside it is to dispatch an action on it, which triggers the root reducer function to calculate the new state.

存储不是一个类。它只是一个带有一些方法的对象。

¥A store is not a class. It's just an object with a few methods on it.

要创建存储,请将你的根 reducer 函数 传递给 Redux Toolkit 的 configureStore 方法,这将设置一个具有良好默认配置的 Redux 存储。(或者,如果你尚未使用 Redux Toolkit,则可以使用原始的 createStore 方法,但我们鼓励你尽快使用 迁移你的代码以使用 Redux Toolkit

¥To create a store, pass your root reducer function to Redux Toolkit's configureStore method, which will set up a Redux store with a good default configuration. (Alternately, if you're not yet using Redux Toolkit, you can use the original createStore method, but we encourage you to migrate your code to use Redux Toolkit as soon as possible)

存储方法

¥Store Methods

getState()

返回应用的当前状态树。它等于存储的 reducer 返回的最后一个值。

¥Returns the current state tree of your application. It is equal to the last value returned by the store's reducer.

返回

¥Returns

(任何):应用的当前状态树。

¥(any): The current state tree of your application.


dispatch(action)

分派一个动作。这是触发状态更改的唯一方法。

¥Dispatches an action. This is the only way to trigger a state change.

存储的 reducer 函数将使用当前的 getState() 结果和给定的 action 同步调用。它的返回值将被视为下一个状态。即日起从 getState() 返回,变更监听者会立即收到通知。

¥The store's reducer function will be called with the current getState() result and the given action synchronously. Its return value will be considered the next state. It will be returned from getState() from now on, and the change listeners will immediately be notified.

提醒

如果你尝试从 reducer 内部调用 dispatch,它将抛出错误,指出 "Reducer 不能调度动作。"Reducers 是纯函数 - 它们只能返回一个新的状态值,并且不能有副作用(并且调度是一个副作用)。

¥If you attempt to call dispatch from inside the reducer, it will throw with an error saying "Reducers may not dispatch actions." Reducers are pure functions - they can only return a new state value and must not have side effects (and dispatching is a side effect).

在 Redux 中,订阅是在根 reducer 返回新状态后调用的,因此你可以在订阅监听器中进行分派。仅不允许你在 reducer 内部调度,因为它们必须没有副作用。如果你想在响应某个操作时产生副作用,那么正确的位置是在潜在的异步 动作创造者 中。

¥In Redux, subscriptions are called after the root reducer has returned the new state, so you may dispatch in the subscription listeners. You are only disallowed to dispatch inside the reducers because they must have no side effects. If you want to cause a side effect in response to an action, the right place to do this is in the potentially async action creator.

参数

¥Arguments

  1. action(对象):一个简单的对象,描述对你的应用有意义的更改。操作是将数据获取到存储中的唯一方法,因此任何数据,无论是来自 UI 事件、网络回调还是其他来源(例如 WebSocket),最终都需要作为操作进行分派。操作必须有一个 type 字段来指示正在执行的操作类型。类型可以定义为常量并从另一个模块导入。对 type 使用字符串比对 符号 使用字符串更好,因为字符串是可序列化的。除了 type 之外,动作对象的结构实际上取决于你。如果你有兴趣,请查看 通量标准作用 以获取有关如何构建操作的建议。

    ¥action (Object): A plain object describing the change that makes sense for your application. Actions are the only way to get data into the store, so any data, whether from the UI events, network callbacks, or other sources such as WebSockets needs to eventually be dispatched as actions. Actions must have a type field that indicates the type of action being performed. Types can be defined as constants and imported from another module. It's better to use strings for type than Symbols because strings are serializable. Other than type, the structure of an action object is really up to you. If you're interested, check out Flux Standard Action for recommendations on how actions could be constructed.

返回

¥Returns

(对象):已调度的操作(请参阅注释)。

¥(Object): The dispatched action (see notes).

注意

¥Notes

通过调用 [`createStore`](/api/createstore) 获得的“普通”存储实现仅支持普通对象操作,并将它们立即交给 reducer。

¥ The “vanilla” store implementation you get by calling createStore only supports plain object actions and hands them immediately to the reducer.

但是,如果用 applyMiddleware 封装 createStore,中间件可以以不同的方式解释操作,并为调度 异步操作 提供支持。异步操作通常是异步原语,例如 Promises、Observables 或 thunk。

¥However, if you wrap createStore with applyMiddleware, the middleware can interpret actions differently, and provide support for dispatching async actions. Async actions are usually asynchronous primitives like Promises, Observables, or thunks.

中间件由社区创建,默认情况下不随 Redux 一起提供。你需要显式安装 redux-thunkredux-promise 等软件包才能使用它。你还可以创建自己的中间件。

¥Middleware is created by the community and does not ship with Redux by default. You need to explicitly install packages like redux-thunk or redux-promise to use it. You may also create your own middleware.

要了解如何描述异步 API 调用、读取操作创建器内的当前状态、执行副作用或将它们链接起来按顺序执行,请参阅 applyMiddleware 的示例。

¥To learn how to describe asynchronous API calls, read the current state inside action creators, perform side effects, or chain them to execute in a sequence, see the examples for applyMiddleware.

示例

¥Example

import { createStore } from 'redux'
const store = createStore(todos, ['Use Redux'])

function addTodo(text) {
return {
type: 'ADD_TODO',
text
}
}

store.dispatch(addTodo('Read the docs'))
store.dispatch(addTodo('Read about the middleware'))

subscribe(listener)

添加更改监听器。每当调度操作时都会调用它,并且状态树的某些部分可能已更改。然后,你可以调用 getState() 来读取回调内的当前状态树。

¥Adds a change listener. It will be called any time an action is dispatched, and some part of the state tree may potentially have changed. You may then call getState() to read the current state tree inside the callback.

你可以从更改监听器调用 dispatch(),但需要注意以下事项:

¥You may call dispatch() from a change listener, with the following caveats:

  1. 监听器应仅在响应用户操作或在特定条件下(例如,当存储具有特定字段时分派操作)调用 dispatch()。在没有任何条件的情况下调用 dispatch() 在技术上是可能的,但是它会导致无限循环,因为每个 dispatch() 调用通常都会再次触发监听器。

    ¥The listener should only call dispatch() either in response to user actions or under specific conditions (e. g. dispatching an action when the store has a specific field). Calling dispatch() without any conditions is technically possible, however it leads to an infinite loop as every dispatch() call usually triggers the listener again.

  2. 订阅会在每次 dispatch() 调用之前进行快照。如果你在调用监听器时订阅或取消订阅,这不会对当前正在进行的 dispatch() 产生任何影响。然而,下一个 dispatch() 调用,无论是否嵌套,都将使用订阅列表的更新快照。

    ¥The subscriptions are snapshotted just before every dispatch() call. If you subscribe or unsubscribe while the listeners are being invoked, this will not have any effect on the dispatch() that is currently in progress. However, the next dispatch() call, whether nested or not, will use a more recent snapshot of the subscription list.

  3. 监听器不应期望看到所有状态更改,因为在调用监听器之前,状态可能已在嵌套 dispatch() 期间更新了多次。但是,可以保证在 dispatch() 启动之前注册的所有订阅者在退出时都将使用最新状态进行调用。

    ¥The listener should not expect to see all state changes, as the state might have been updated multiple times during a nested dispatch() before the listener is called. It is, however, guaranteed that all subscribers registered before the dispatch() started will be called with the latest state by the time it exits.

它是一个底层 API。最有可能的是,你将使用 React(或其他)绑定,而不是直接使用它。如果你通常使用回调作为钩子来对状态更改做出反应,你可能需要 编写自定义 observeStore 实用程序Store 也是 Observable,因此你可以使用 subscribe 等库来更改 接收 JS

¥It is a low-level API. Most likely, instead of using it directly, you'll use React (or other) bindings. If you commonly use the callback as a hook to react to state changes, you might want to write a custom observeStore utility. The Store is also an Observable, so you can subscribe to changes with libraries like RxJS.

要取消订阅更改监听器,请调用 subscribe 返回的函数。

¥To unsubscribe the change listener, invoke the function returned by subscribe.

参数

¥Arguments

  1. listener(功能):每当调度操作时都会调用回调,并且状态树可能已更改。你可以在该回调中调用 getState() 来读取当前状态树。可以合理地预期存储的 reducer 是纯函数,因此你可以比较对状态树中某些深层路径的引用以了解其值是否已更改。

    ¥listener (Function): The callback to be invoked any time an action has been dispatched, and the state tree might have changed. You may call getState() inside this callback to read the current state tree. It is reasonable to expect that the store's reducer is a pure function, so you may compare references to some deep path in the state tree to learn whether its value has changed.

返回

¥Returns

(功能):取消订阅更改监听器的函数。

¥(Function): A function that unsubscribes the change listener.

示例

¥Example

function select(state) {
return state.some.deep.property
}

let currentValue
function handleChange() {
let previousValue = currentValue
currentValue = select(store.getState())

if (previousValue !== currentValue) {
console.log(
'Some deep nested property changed from',
previousValue,
'to',
currentValue
)
}
}

const unsubscribe = store.subscribe(handleChange)
unsubscribe()

replaceReducer(nextReducer)

替换 store 当前用于计算状态的 reducer。

¥Replaces the reducer currently used by the store to calculate the state.

它是一个高级 API。如果你的应用实现代码分割,并且你想要动态加载一些 reducer,你可能需要这个。如果你为 Redux 实现热重载机制,你可能还需要这个。

¥It is an advanced API. You might need this if your app implements code splitting, and you want to load some of the reducers dynamically. You might also need this if you implement a hot reloading mechanism for Redux.

参数

¥Arguments

  1. nextReducer(功能)存储使用的下一个 reducer。

    ¥nextReducer (Function) The next reducer for the store to use.