我有一个reducer,它从某个列表中维护当前可见的项目,并显示下一个和上一个项目的情况:
export function currentIndex(state = null, action) {
switch (action.type) {
case types.INCREMENT:
return state + 1
case types.DECREMENT:
return state - 1;
}
}
我也有一个random
状态,最初是假的但是当设置为true时我希望currentListItem
reducer能够解释这个并输出一个随机数。
在redux中执行此操作的最惯用方法是什么?
答案 0 :(得分:2)
惯用解决方案是使用中间件包redux-thunk(或类似)将您的reducer逻辑转移到thunk中。
这允许您将特殊类型的actions
视为函数,这意味着您可以使用特定的与操作相关的逻辑扩展普通操作。您给出需要访问状态以有条件地确定动作逻辑的示例是redux-thunk的一个很好的用例。
下面是一个如何将逻辑从reducer中拉出来的示例。您应该注意,与reducers不同,thunk明确支持获取状态并通过getState
和dispatch
函数调度后续操作。
Thunk示例
export const increment= () => {
return (dispatch, getState) => {
const state = getState()
const delta = (state.random) ? getRandomNumber() : 1
dispatch({
type: INCREMENT,
delta
})
}
}
export function currentIndex(state = null, action) {
switch (action.type) {
case types.INCREMENT:
return state + action.delta
}
}