【React】如何在redux中的reducer方法中调用其他reducer?或者reducer中获取全局的state
在程序中我有两个reducer: clock与todo。clock是个倒计时闹钟程序,
todo是任务管理。
于是需要在执行clock的reducer修改todo中的状态。
回答
看了你的問題直覺能想到的大方向有兩種
將 clock 放到 todos 底下但這種方式長遠來說會越來越複雜
另一個方式就是靠 thunk
// This is only for clockconst clockInitialState = {
second: 5,
minute: 0,
runningType: 0 // 0: initial, 1: running, 2: done
}
function clock (state = clockInitialState, action) {
let allSecond = state.minute * 60 + state.second
let currentSecond = allSecond - 1
let minute = Math.floor(currentSecond / 60);
let second = currentSecond % 60
let runningType = currentSecond === 0 ? 2 : 1;
switch (action.type) {
case COUNT_DOWN:
return {
...state,
minute: minute,
second: second,
runningType: runningType
}
case COUNT_RESET:
return clockInitialState
default:
return state
}
}
export const COUNT_DOWN = 'COUNT_DOWN'export const COUNT_RESET = 'COUNT_RESET'
export function countDown() {
return {
type: COUNT_DOWN
}
}
export function countReset() {
return {
type: COUNT_RESET
}
}
// thunk
export function runCountDown() {
return (dispatch, getState) => {
let p = new Promise(function(resolve, reject) {
let timer = setInterval(() => {
console.log('!!');
let { clock } = getState()
if (clock.runningType === 2) {
clearInterval(timer)
resolve()
} else {
dispatch(countDown())
}
}, 1000)
})
return p.then(() => dispatch(addTodo('A')))
.then(() => dispatch(addTodo('B')))
}
}
我不確定這是最好的辦法但以我現階段的知識只能想出這個解法
dispatch一个action,只要是同一个action type,在各个reducer中都可以接收到,各自修改各自的state
以上是 【React】如何在redux中的reducer方法中调用其他reducer?或者reducer中获取全局的state 的全部内容, 来源链接: utcz.com/a/75550.html