我认为您将 reducer 的 initial 状态与应用的全局状态混淆了。
全局状态仅表示应用中所有 reducer 的组合状态。
为简单起见,我们假设您的应用中只有一个 reducer。
减速机:
function todos(state = [], action) {
switch (action.type) {
case 'ADD_TODO':
return state.concat([action.text])
default:
return state
}
}
所以这个简单的函数todos 是我们的reducer,它会在运行时为我们提供当前状态树。
所以这是createStore的第一个参数。
初始状态:
['Understanding Store']
让我们假设我们的初始状态是一个包含 1 个项目的数组,如上所示。
这将是createStore 的第二个参数。
现在我们像这样创建我们的商店:
import { createStore } from 'redux'
//... code
.
.
.
const store = createStore(todos, ['Understanding Store'])
现在我们的商店已创建。
没什么特别的,store 基本上是一个对象,上面没有什么方法。
其中一种方法是dispatch。
这个方法有助于dispatching 一个动作,它会通过我们的reducer然后更新状态。
所以当我们这样做时
store.dispatch({
type: 'ADD_TODO',
text: 'Learn methods on Store'
})
这将更新我们的状态如下:
['Understanding Store','Learn methods on Store']
但是当您的应用变大时,您可能希望创建不同的函数(reducer)来管理全局状态的不同部分。
如果我们还有一个 reducer,请说counter.js:
export default function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
然后,为了结合我们的第一个 reducer todos 和这个 counter reducer,我们有一个名为 combineReducer 的实用程序。
rootReducer.js
import { combineReducers } from 'redux'
import todos from './todos'
import counter from './counter'
export default combineReducers({
todos,
counter
})
然后使用createStore,您只需这样做:
import { createStore } from 'redux'
import rootReducer from './rootReducer.js;
const store = createStore(rootReducer);
在使用combineReducers 时,您需要遵守一些规则。
阅读规则here