我是Redux的新手,立即引起我的注意的是Reducers开启类型。为什么Redux使用开关而不是利用多态行为?
下面是来自Vanilla Counter example的摘录:
function counter(state, action) {
if (typeof state === 'undefined') {
return 0
}
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
// details omitted
document.getElementById('increment')
.addEventListener('click', function() {
store.dispatch({ type: 'INCREMENT' })
})
document.getElementById('decrement')
.addEventListener('click', function() {
store.dispatch({ type: 'DECREMENT' })
})
为什么不使用它是这样的呢?
function increment(state) { return state + 1; }
function decrement(state) { return state - 1; }
function counter(state, action) {
if (typeof state === 'undefined') {
return 0
}
return action.handler(state);
}
// details omitted
document.getElementById('increment')
.addEventListener('click', function() {
store.dispatch({ handler: increment, type: 'unused' })
})
document.getElementById('decrement')
.addEventListener('click', function() {
store.dispatch({ handler: decrement, type: 'unused' })
})
如果你喜欢,你可以做到这一点,REDX。来自Dan Abramov:Redux并不认为你是如何创建减速器的,所以你可以使用任何你喜欢的惯例 – JordanHendrix