簡體   English   中英

如何將狀態更改操作提取到具有類型參數的命名函數? NgRx,角度

[英]How extract state change action to a named function with typed parameters? NgRx, Angular

有沒有辦法創建一個命名狀態更改函數,具有適當的參數類型,在創建減速器時將在on方法中接受?

我想創建onLoginSuccessful函數,該函數將處理狀態更改並可以傳遞給減速器中的on方法。

但是當我嘗試創建onLoginSuccessful時,出現 TS 編譯錯誤。

//== actions.ts file ==//
export const loginSuccessful = createAction(
    '[Login page] Login successful',
    props<{authToken: string}>()
);

//== reducer.ts file ==//
export const initialState: AuthState = {
    authToken: null
};

// this works
export const reducer = createReducer(
    initialState,
    on(loginSuccessful, (state, action) => {
        return {
            ...state,
            authToken: action.authToken
        };
    })
);

// this does NOT work
// creating named function onLoginSuccess with typed params
function onLoginSuccess(state: AuthState, action: typeof loginSuccessful): AuthState {
    return {
        ...state,
        authToken: action.authToken
    };
}

export const reducer = createReducer(
    initialState,
    on(loginSuccessful, onLoginSuccess) // <-- here on "onLoginSuccess" param throws TS compiler an error
);

TS編譯錯誤:

'(state: AuthState, action: ActionCreator<"[登錄頁面] 登錄成功", (props: { authToken: string; }) => { authToken: string; } & TypedAction<"[登錄頁面] 登錄成功的參數">>) => AuthState' 不能分配給類型為 'OnReducer<AuthState, [ActionCreator<"[Login page] 登錄成功的參數", (props: { authToken: string; }) => { authToken: string; } & TypedAction<"[登錄頁面]登錄成功">>]>'. 參數“action”和“action”的類型不兼容。 輸入 '{ authToken: 字符串; } & TypedAction<"[登錄頁面] 登錄成功"> & { type: "[登錄頁面] 登錄成功"; }' 不可分配到類型 'ActionCreator<"[登錄頁面] 登錄成功", (props: { authToken: string; }) => { authToken: string; } & TypedAction<"[登錄頁面]登錄成功">>'. 輸入 '{ authToken: 字符串; } & TypedAction<"[登錄頁面] 登錄成功"> & { type: "[登錄頁面] 登錄成功"; }' 不可分配給類型 '(props: { authToken: string; }) => { authToken: string; } & TypedAction<"[登錄頁面]登錄成功">'。 輸入 '{ authToken: 字符串; } & TypedAction<"[登錄頁面] 登錄成功"> & { type: "[登錄頁面] 登錄成功"; }' 不匹配簽名 '(props: { authToken: string; }): { authToken: string; } & TypedAction<"[登錄頁面]登錄成功">'.ts(2345)

嘗試使用ActionType<typeof loginSuccessful>

import { ActionType } from "@ngrx/store";

// ...

function onLoginSuccess(state: AuthState, action: ActionType<typeof loginSuccessful>): AuthState {
  return {
    ...state,
    authToken: action.authToken
  };
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM