Skip to main content

createStore(reducer, preloadedState?, enhancer?)

创建一个 Redux store 来保存应用的完整状态树。你的应用中应该只有一个存储。

¥Creates a Redux store that holds the complete state tree of your app. There should only be a single store in your app.

危险

原来的 Redux core createStore 方法已被弃用!

¥The original Redux core createStore method is deprecated!

createStore 将无限期地继续工作,但我们不鼓励直接使用 createStore 或原始 redux 包。

¥createStore will continue to work indefinitely, but we discourage direct use of createStore or the original redux package.

相反,你应该使用我们官方 Redux 工具包 包中的 configureStore 方法,它封装了 createStore 以提供更好的默认设置和配置方法。你还应该使用 Redux Toolkit 的 createSlice 方法 来编写 reducer 逻辑。

¥Instead, you should use the configureStore method from our official Redux Toolkit package, which wraps createStore to provide a better default setup and configuration approach. You should also use Redux Toolkit's createSlice method for writing reducer logic.

Redux Toolkit 还重新导出 redux 包中包含的所有其他 API。

¥Redux Toolkit also re-exports all of the other APIs included in the redux package as well.

有关如何更新现有旧 Redux 代码库以使用 Redux Toolkit 的详细信息,请参阅 迁移到 Modern Redux 页面

¥See the Migrating to Modern Redux page for details on how to update your existing legacy Redux codebase to use Redux Toolkit.

参数

¥Arguments

  1. reducer(功能):给定当前状态树和要处理的 action,根 reducer 函数 返回下一个 状态树

    ¥reducer (Function): A root reducer function that returns the next state tree, given the current state tree and an action to handle.

  2. [preloadedState](任意):初始状态。你可以选择指定它来混合通用应用中服务器的状态,或恢复以前序列化的用户会话。如果你使用 combineReducers 生成了 reducer,则这必须是一个普通对象,其形状与传递给它的键相同。否则,你可以随意传递你的 reducer 可以理解的任何内容。

    ¥[preloadedState] (any): The initial state. You may optionally specify it to hydrate the state from the server in universal apps, or to restore a previously serialized user session. If you produced reducer with combineReducers, this must be a plain object with the same shape as the keys passed to it. Otherwise, you are free to pass anything that your reducer can understand.

  3. [enhancer](功能):存储增强器。你可以选择指定它来通过第三方功能(例如中间件、时间旅行、持久性等)增强存储。Redux 附带的唯一存储增强器是 applyMiddleware()

    ¥[enhancer] (Function): The store enhancer. You may optionally specify it to enhance the store with third-party capabilities such as middleware, time travel, persistence, etc. The only store enhancer that ships with Redux is applyMiddleware().

返回

¥Returns

Store):保存应用完整状态的对象。改变其状态的唯一方法是通过 调度动作。你还可以通过更改其状态来更新 UI。

¥(Store): An object that holds the complete state of your app. The only way to change its state is by dispatching actions. You may also subscribe to the changes to its state to update the UI.

示例

¥Example

import { createStore } from 'redux'

function todos(state = [], action) {
switch (action.type) {
case 'ADD_TODO':
return state.concat([action.text])
default:
return state
}
}

const store = createStore(todos, ['Use Redux'])

store.dispatch({
type: 'ADD_TODO',
text: 'Read the docs'
})

console.log(store.getState())
// [ 'Use Redux', 'Read the docs' ]

弃用和备用 legacy_createStore 导出

¥Deprecation and Alternate legacy_createStore Export

Redux 4.2.0,我们将原来的 createStore 方法标记为 @deprecated 年。严格来说,这不是一个重大更改,也不是 5.0 中的新内容,但为了完整起见,我们在这里记录它。

¥In Redux 4.2.0, we marked the original createStore method as @deprecated. Strictly speaking, this is not a breaking change, nor is it new in 5.0, but we're documenting it here for completeness.

此弃用只是一个视觉指示器,旨在鼓励用户 将他们的应用从旧版 Redux 模式迁移到使用现代 Redux Toolkit API。弃用会导致导入和使用时出现视觉删除线,如 createStore,但不会出现运行时错误或警告。

¥This deprecation is solely a visual indicator that is meant to encourage users to migrate their apps from legacy Redux patterns to use the modern Redux Toolkit APIs. The deprecation results in a visual strikethrough when imported and used, like createStore, but with no runtime errors or warnings.

createStore 将无限期地继续工作,并且永远不会被删除。但是,今天我们希望所有 Redux 用户都使用 Redux Toolkit 来实现所有 Redux 逻辑。

¥createStore will continue to work indefinitely, and will not ever be removed. But, today we want all Redux users to be using Redux Toolkit for all of their Redux logic.

要解决此问题,有以下三个选项:

¥To fix this, there are three options:

  • 按照我们的强烈建议切换到 Redux Toolkit 和 configureStore

    ¥Follow our strong suggestion to switch over to Redux Toolkit and configureStore

  • 没做什么。这只是一个视觉删除线,它不会影响代码的行为方式。忽略它。

    ¥Do nothing. It's just a visual strikethrough, and it doesn't affect how your code behaves. Ignore it.

  • 切换到使用现在导出的 legacy_createStore API,这是完全相同的函数,但没有 @deprecated 标签。最简单的选择是执行别名导入重命名,例如 import { legacy_createStore as createStore } from 'redux'

    ¥Switch to using the legacy_createStore API that is now exported, which is the exact same function but with no @deprecated tag. The simplest option is to do an aliased import rename, like import { legacy_createStore as createStore } from 'redux'

提示

¥Tips

  • 不要在一个应用中创建多个存储!相反,使用 combineReducers 从多个根 reducer 中创建一个单个根 reducer。

    ¥Don't create more than one store in an application! Instead, use combineReducers to create a single root reducer out of many.

  • Redux 状态通常是纯 JS 对象和数组。

    ¥Redux state is normally plain JS objects and arrays.

  • 如果你的状态是一个普通对象,请确保你永远不会改变它!不可变更新需要复制每个级别的数据,通常使用对象扩展运算符 (return { ...state, ...newData })。

    ¥If your state is a plain object, make sure you never mutate it! Immutable updates require making copies of each level of data, typically using the object spread operator ( return { ...state, ...newData } ).

  • 对于在服务器上运行的通用应用,请为每个请求创建一个存储实例,以便将它们隔离。将一些数据获取操作分派到存储实例并等待它们完成,然后再在服务器上渲染应用。

    ¥For universal apps that run on the server, create a store instance with every request so that they are isolated. Dispatch a few data fetching actions to a store instance and wait for them to complete before rendering the app on the server.

  • 创建存储后,Redux 会向你的 reducer 分派一个虚拟操作,以使用初始状态填充存储。你不应该直接处理虚拟操作。请记住,如果作为第一个参数提供给它的状态是 undefined,那么你的 reducer 应该返回某种初始状态,并且你已准备就绪。

    ¥When a store is created, Redux dispatches a dummy action to your reducer to populate the store with the initial state. You are not meant to handle the dummy action directly. Just remember that your reducer should return some kind of initial state if the state given to it as the first argument is undefined, and you're all set.

  • 要应用多个存储增强器,你可以使用 compose()

    ¥To apply multiple store enhancers, you may use compose().