TypedAction
是一个通用接口,通过添加只读type
属性扩展了Action类型。
export declare interface TypedAction<T extends string> extends Action {
readonly type: T;
}
ActionCreator<T,() => TypedAction<T>>
-告诉我们,我们有一个工厂返回TypedAction对象() => ({ type: T})
让我们定义一个动作创建者:
export const logout = createAction('[Auth] Logout');
createAction
函数在action_creator.ts中定义。
export function createAction<T extends string>(
type: T
): ActionCreator<T,() => TypedAction<T>>;
从声明中我们可以知道createAction
将返回一个函数,该函数反过来返回一个对象,该对象的字符串属性为type
让我们深入探讨一下实际的实现。
当您不为动作创建者the following code is executed提供有效载荷时:
<T extends string>
defineType是:
export function createAction<T extends string,C extends Creator>(
type: T,config?: { _as: 'props' } | C
): Creator {
...
case 'empty':
return defineType(type,() => ({ type }));
...
}
function defineType(type: string,creator: Creator): Creator {
return Object.defineProperty(creator,'type',{
value: type,writable: false,});
}
接受类型(“ [Auth]注销”)和创建者-defineType
。它返回创建者,但是具有新属性() => ({ type })
。
因此,调用type
和logout.type
将返回相同的值-'[Auth]注销'
稍后,在reducer_creator.ts中,它允许我们extract ActionCreator type(在本例中为“ [Auth]注销”),将其与reducer函数关联,并与execute it
更新:
随着问题的答案越来越大,我决定写一篇博客文章How do NgRx Action Creators work
本文链接:https://www.f2er.com/3167993.html