Redux 不会强制你使用默认的参数语法。它只关心当它为您提供undefined 作为状态时,您返回其他内容,以便您的应用能够以初始状态树启动。
ES6 中的这个函数:
function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state + 1
default:
return state
}
}
相当于ES5中的这个函数:
function counter(state, action) {
if (state === undefined) {
state = 0
}
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state + 1
default:
return state
}
}
验证这一点的好方法是run this code through the Babel REPL。
我进行递归调用的原因是我非常重视“状态是不可变的”。所以即使状态参数未定义,我也不会更改参数变量本身。
这里不需要递归调用。我认为您的问题可能对变异和参考分配之间的区别有些混淆。
当你写作时
var x = { lol: true }
x.lol = false
你正在变异 x 对象。这是 Redux 所不允许的。
但是当你写的时候
var x = { lol: true }
x = { lol: false }
原始对象保持不变。 x“绑定”(也称为“变量”)只是开始指向不同的对象。
Redux 不在乎您是否更改 state 参数所指的内容。它对您的功能是本地的。无论您是否返回它,都可以更改引用只要您不改变实际对象或其中的任何对象。
仅更改变量所指的内容不会改变对象:
// good: local variable called "state" refers to a different number
state = state + 1
// good: local variable called "state" refers to a different array
state = state.concat([42])
// good: local variable called "state" refers to a different string
state = state + ", lol"
然而,改变对象本身或它链接到的对象,无论是否深入,都是一种突变,Redux 不允许:
// bad: object that local variable "state" refers to has been mutated
state.counter = state.counter + 1
// bad: object that local variable "state" refers to has been mutated
var sameObjectAsState = state
state.counter = state.counter + 1
// bad: array that local variable "state" refers to has been mutated
state.push(42)
// bad: array that local variable "state" refers to has been mutated
var sameArrayAsState = state
sameArrayAsState.push(42)
// bad: object that is linked from the object that local variable "state" refers to has been mutated
state.something.deep.counter = 42
// bad: object that is linked from the object that local variable "state" refers to has been mutated
var somethingDeep = state.something.deep
somethingDeep.counter = 42