我是Redux的新手,立刻引起我注意的是Reducers打开了类型.
以下是Vanilla Counter示例的摘录:
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' })
})
Run Code Online (Sandbox Code Playgroud)
为什么不使用这样的东西呢?
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' })
})
Run Code Online (Sandbox Code Playgroud)
因此,您不希望将其置于操作中的重要原因是您的商店中的多个节点可能想要响应相同的操作.
dispatch({ type: "USER_LOGIN", payload: user });
Run Code Online (Sandbox Code Playgroud)
这可能user需要对操作做出反应,它可能希望标头/登录/注销功能做出反应,它可能希望您所在的页面做出反应,或者访问级别做出反应.
如果你已经追平了数据页面的行为的行为,那么你已经删除了这种能力,和排序的否定了两者之间的分离.
绝对没有理由不能使用策略模式(而不是开关)并在那里使用您的功能.
function (state, action) {
const strategy = {
INCREMENT: increment,
DECREMENT: decrement,
default: identity
};
return (strategy[action.type] || strategy.default)(state, action);
}
Run Code Online (Sandbox Code Playgroud)
increment在其他嵌套节点上,etc函数将在需要进一步缩减的情况下采用状态和动作.
| 归档时间: |
|
| 查看次数: |
243 次 |
| 最近记录: |