createStore(reducer, [initialState])
創(chuàng)建一個 Redux store 來以存放應用中所有的 state。應用中應有且僅有一個 store。
reducer
(Function): 接收兩個參數,分別是當前的 state 樹和要處理的 action,返回新的 state 樹。
[initialState
] (any): 初始時的 state。在同構應用中,你可以決定是否把服務端傳來的 state 水合(hydrate)后傳給它,或者從之前保存的用戶會話中恢復一個傳給它。如果你使用 combineReducers
創(chuàng)建 reducer
,它必須是一個普通對象,與傳入的 keys 保持同樣的結構。否則,你可以自由傳入任何 reducer
可理解的內容。[TODO: Optimize]
(Store
): 保存了應用所有 state 的對象。改變 state 的惟一方法是 dispatch action。你也可以 subscribe 監(jiān)聽 state 的變化,然后更新 UI。
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']
應用中不要創(chuàng)建多個 store!相反,使用 combineReducers
來把多個 reducer 創(chuàng)建成一個根 reducer。
你可以決定 state 的格式。你可以使用普通對象或者 Immutable 這類的實現。如果你不知道如何做,剛開始可以使用普通對象。
如果 state 是普通對象,永遠不要修改它!比如,reducer 里不要使用 Object.assign(state, newData)
,應該使用 Object.assign({}, state, newData)
。這樣才不會覆蓋舊的 state
。也可以使用 Babel 階段 1 中的 ES7 對象的 spread 操作 特性中的 return { ...state, ...newData }
。
對于服務端運行的同構應用,為每一個請求創(chuàng)建一個 store 實例,以此讓 store 相隔離。dispatch 一系列請求數據的 action 到 store 實例上,等待請求完成后再在服務端渲染應用。
當 store 創(chuàng)建后,Redux 會 dispatch 一個 action 到 reducer 上,來用初始的 state 來填充 store。你不需要處理這個 action。但要記住,如果第一個參數也就是傳入的 state 如果是 undefined
的話,reducer 應該返回初始的 state 值。
更多建議: