如何为 combineReducers 提供正确的状态切片

How does combineReducers being provided with the right state slices

我对 Redux 很陌生。

我一直在阅读它的 Reducers documentation、运行 到我似乎无法理解的 combineReducers 函数中。

他们注意到:

All combineReducers() does is generate a function that calls your reducers with the slices of state selected according to their keys, and combining their results into a single object again. It's not magic.

我确实理解 returns 一个组合的减速器,就像它听起来的那样,但是它如何为每个减速器提供特定的相关 状态片 - according to their keys是什么意思?

深入研究他们的 It's not magic git 问题帮助我更多地了解 combineReducers 的使用,但我仍然无法理解 根据他们的密钥 段。

任何解释将不胜感激,谢谢。

A:如果你的 state 切片和 reducer 函数有相似的名字——那个 slice 会提供那个 reducer。

示例:

const state = {
  slice1 : {...},
  slice2 : {...}
}

function slice1(state, action){...}
function slice2(state, action){...}

combineReducers({slice1, slice2})   //Reducers will be provided with appropriate slices.

B:如果您为 combineReducers 函数提供键,这些键必须与状态切片键匹配。

示例:

const state = {
  slice1 : {...},
  slice2 : {...}
}

function reducer1(state, action){...}
function reducer2(state, action){...}

combineReducers({slice1 : reducer1, 
                 slice2 : reducer2})   //Reducers will be provided with appropriate slices.

C:两种方法可以混合使用:

示例:

const state = {
  slice1 : {...},
  slice2 : {...}
}

function slice1(state, action){...}
function reducer2(state, action){...}

combineReducers({slice1, 
                 slice2 : reducer2})   //Reducers will be provided with appropriate slices.

我认为如果您不真正熟悉新的 ES6 语法,可能会出现一些混淆。

如果你查看 redux 文档,你会发现他们使用 ES6 object literal shorthand syntax 来定义对象形状

const rootReducer = combineReducers({
    theDefaultReducer,
    firstNamedReducer,
    secondNamedReducer
});

这个简写实际上可以翻译成:

var rootReducer = combineReducers({
    theDefaultReducer: theDefaultReducer,
    firstNamedReducer: firstNamedReducer,
    secondNamedReducer: secondNamedReducer
});

如您所见,键与单独的单个 reducer 匹配,这样 combineReducers 就知道要映射什么。