Thunk 是包装表达式的函数,以延迟它们的求值。
这个延迟是在 Redux thunk 中实现的,当一个动作被调用时它会返回一个函数。返回的这个函数可以在以后调用。
这里是一个 thunk 动作的例子。
function incrementAsync() {
// the below function is called by Redux Thunk middleware below.
return dispatch => {
setTimeout(() => {
// Yay! Can invoke sync or async actions with `dispatch`
dispatch(increment());
}, 1000);
};
高阶函数只是一个返回函数或将函数作为其参数之一的函数。因为这个函数返回另一个以 dispatch 作为参数的函数,所以这是一个高阶函数的例子。
redux thunk 中间件的代码类似于这样
function createThunkMiddleware() {
return store => next => action => {
if (typeof action === 'function') {
// since action is a function it is a thunk action creator
// so call it with store methods
return action(store.dispatch, store.getState);
}
// action is not a function so redux thunk ignores it
return next(action);
};
}
一旦我们的 thunk 动作创建者被调用,它就会通过中间件链发送动作函数。当它到达我们的 thunk 中间件时,这个动作被识别为一个函数,因此使用 store 的 dispatch 和 getState 方法再次调用。
由于第二个函数调用,我们现在处于 thunk 动作创建者返回函数的范围内。这意味着我们现在可以执行异步逻辑并且仍然可以访问 store 的 getState 和 dispatch 方法。这就是为什么我们的 thunk action creator 可以被认为是一个 thunk 表达式。通过使用高阶函数,我们可以访问,但推迟使用 store 的 dispatch 或 getState 方法到未来时间。如下所示,增量动作在一秒延迟后被调用。
function incrementAsync() {
// the below function is called by Redux Thunk middleware below.
return dispatch => {
setTimeout(() => {
// Yay! Can invoke sync or async actions with `dispatch`
dispatch(increment());
}, 1000);
};