# `createStore(reducer, [preloadedState], enhancer)`
創建一個 Redux [store](Store.md) 來以存放應用中所有的 state。
應用中應有且僅有一個 store。
#### 參數
1. `reducer` _(Function)_: 接收兩個參數,分別是當前的 state 樹和要處理的 [action](../Glossary.md#action),返回新的 [state 樹](../Glossary.md#state)。
2. [`preloadedState`] _(any)_: 初始時的 state。
在同構應用中,你可以決定是否把服務端傳來的 state 水合(hydrate)后傳給它,或者從之前保存的用戶會話中恢復一個傳給它。如果你使用 [`combineReducers`](combineReducers.md) 創建 `reducer`,它必須是一個普通對象,與傳入的 keys 保持同樣的結構。否則,你可以自由傳入任何 `reducer` 可理解的內容。
3. `enhancer` _(Function)_: Store enhancer 是一個組合 store creator 的高階函數,返回一個新的強化過的 store creator。這與 middleware 相似,它也允許你通過復合函數改變 store 接口。
#### 返回值
([_`Store`_](Store.md)): 保存了應用所有 state 的對象。改變 state 的惟一方法是 [dispatch](Store.md#dispatch) action。你也可以 [subscribe 監聽](Store.md#subscribe) state 的變化,然后更新 UI。
#### 示例
```js
import { createStore } from 'redux'
function todos(state = [], action) {
switch (action.type) {
case 'ADD_TODO':
return state.concat([action.text])
default:
return state
}
}
let store = createStore(todos, ['Use Redux'])
store.dispatch({
type: 'ADD_TODO',
text: 'Read the docs'
})
console.log(store.getState())
// [ 'Use Redux', 'Read the docs' ]
```
#### 小貼士
- 應用中不要創建多個 store!相反,使用 [`combineReducers`](combineReducers.md) 來把多個 reducer 創建成一個根 reducer。
- 你可以決定 state 的格式。你可以使用普通對象或者 [Immutable](http://facebook.github.io/immutable-js/) 這類的實現。如果你不知道如何做,剛開始可以使用普通對象。
- 如果 state 是普通對象,永遠不要修改它!比如,reducer 里不要使用 `Object.assign(state, newData)`,應該使用 `Object.assign({}, state, newData)`。這樣才不會覆蓋舊的 `state`。如果可以的話,也可以使用 [對象拓展操作符(object spread spread operator](https://github.com/sebmarkbage/ecmascript-rest-spread) 特性中的 `return { ...state, ...newData }`。
- 對于服務端運行的同構應用,為每一個請求創建一個 store 實例,以此讓 store 相隔離。dispatch 一系列請求數據的 action 到 store 實例上,等待請求完成后再在服務端渲染應用。
- 當 store 創建后,Redux 會 dispatch 一個 action 到 reducer 上,來用初始的 state 來填充 store。你不需要處理這個 action。但要記住,如果第一個參數也就是傳入的 state 是 `undefined` 的話,reducer 應該返回初始的 state 值。
- 要使用多個 store 增強器的時候,你可能需要使用 [compose](./compose.md)
- 自述
- 介紹
- 動機
- 核心概念
- 三大原則
- 先前技術
- 學習資源
- 生態系統
- 示例
- 基礎
- Action
- Reducer
- Store
- 數據流
- 搭配 React
- 示例:Todo List
- 高級
- 異步 Action
- 異步數據流
- Middleware
- 搭配 React Router
- 示例:Reddit API
- 下一步
- 技巧
- 配置 Store
- 遷移到 Redux
- 使用對象展開運算符
- 減少樣板代碼
- 服務端渲染
- 編寫測試
- 計算衍生數據
- 實現撤銷重做
- 子應用隔離
- 組織 Reducer
- Reducer 基礎概念
- Reducer 基礎結構
- Reducer 邏輯拆分
- Reducer 重構示例
- combineReducers 用法
- combineReducers 進階
- State 范式化
- 管理范式化數據
- Reducer 邏輯復用
- 不可變更新模式
- 初始化 State
- 結合 Immutable.JS 使用 Redux
- 常見問題
- 綜合
- Reducer
- 組織 State
- 創建 Store
- Action
- 不可變數據
- 代碼結構
- 性能
- 設計哲學
- React Redux
- 其它
- 排錯
- 詞匯表
- API 文檔
- createStore
- Store
- combineReducers
- applyMiddleware
- bindActionCreators
- compose
- react-redux 文檔
- API
- 排錯