创建一个 Redux store 来以存放应用中所有的 state。
应用中应有且仅有一个 store。
参数
-
reducer(Function): 接收两个参数,分别是当前的 state 树和要处理的 action,返回新的 state 树。 -
[
initialState] (any): 初始时的 state。 在同构应用中,你可以决定是否把服务端传来的 state 水合(hydrate)后传给它,或者从之前保存的用户会话中恢复一个传给它。如果你使用combineReducers创建reducer,它必须是一个普通对象,与传入的 keys 保持同样的结构。否则,你可以自由传入任何reducer可理解的内容。
返回值
(Store): 保存了应用所有 state 的对象。改变 state 的惟一方法是 dispatch action。你也可以 subscribe 监听 state 的变化,然后更新 UI。
1 import { createStore } from 'redux' 2 3 function todos(state = [], action) { 4 switch (action.type) { 5 case 'ADD_TODO': 6 return state.concat([ action.text ]) 7 default: 8 return state 9 } 10 } 11 12 let store = createStore(todos, [ 'Use Redux' ]) 13 14 store.dispatch({ 15 type: 'ADD_TODO', 16 text: 'Read the docs' 17 }) 18 19 console.log(store.getState()) 20 // [ 'Use Redux', 'Read the docs' ]