gpt4 book ai didi

angular - @ngrx/store 从 v10 更新到 v11/v12

转载 作者:行者123 更新时间:2023-12-04 14:06:05 25 4
gpt4 key购买 nike

美好的一天。

我需要帮助解决以下问题。不久前,我们将项目更新为使用 Angular 12,我一直在尝试将 @ngrx/store 从 v10 更新到 v11(或 v12)。当我们还在使用 Angular 11 时,我确实尝试过此更新,但我不断收到此错误:

Argument of type 'ReducerTypes<unknown, [ActionCreator<"EnableForm", () => TypedAction<"EnableForm">>]>' is not assignable to parameter of type 'ReducerTypes<AppState, ActionCreator<string, Creator<any[], object>>[]>'.
Types of property 'reducer' are incompatible.
Type 'OnReducer<unknown, [ActionCreator<"EnableForm", () => TypedAction<"EnableForm">>]>' is not assignable to type 'OnReducer<AppState, ActionCreator<string, Creator<any[], object>>[]>'.
Type 'unknown' is not assignable to type 'AppState'.

我的 reducer 看起来像这样:

import { Action, createReducer, on } from '@ngrx/store';
import * as MyAction from '../actions';
import { AppState } from '../state';
import { onEnableForm, onDisableForm } from './form.reducer';

const initialState: AppState = {
form: {
disabled: false,
...
},
...
};
export function storeReducer(state: AppState = initialState, action: Action): AppState {
return createReducer<AppState>(
state,
on(MyAction.InitializeState, MyAction.ResetState, () => initialState),
on(MyAction.DestroyState, () => undefined),
onEnableForm,
onDisableForm
)(state, action);
}

actions.ts 看起来像这样:

import { createAction } from '@ngrx/store';

export const InitializeState = createAction('[MyFeatureStore] InitializeState');

export const ResetState = createAction('[MyFeatureStore] ResetState');

export const DestroyState = createAction('[MyFeatureStore] DestroyState');

export const EnableForm = createAction('[MyFeatureStore] EnableForm');

export const DisableForm = createAction('[MyFeatureStore] DisableForm');

form.reducer.ts 看起来像这样:

import { on } from '@ngrx/store';
import * as MyAction from '../actions';
import { AppState } from '../state';

export const onEnableForm = on(MyAction.EnableForm, (state: AppState) => {
return {
...state,
form: {
...state.form,
disabled: false
}
};
});
export const onDisableForm = on(MyAction.DisableForm, (state: AppState) => {
return {
...state,
form: {
...state.form,
disabled: true
}
};
});

这在 v10 中工作正常,但我不明白为什么它在 v11 中不工作。

最佳答案

正在发生的事情是 Angular 和所有 typescript 世界都在转向越来越强类型的规则,所以当你在管道外创建 on 函数时, typescript 无法推断出什么是继续。

你可以做的就是像这样扩展你的on函数的类型

export const onEnableForm = on<AppState, any>(EnableForm, (state: AppState): AppState => {
return {
...state,
form: {
...state.form,
disabled: false,
}
};
});
export const onDisableForm = on<AppState, any>(
DisableForm,
(state: AppState): AppState => {
return {
...state,
form: {
...state.form,
disabled: true
}
};
}
);

在找到合适的类型来代替 any 之前,您可以使用它作为解决方法。这是一个stackblitz与建议的解决方案。

关于angular - @ngrx/store 从 v10 更新到 v11/v12,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68453500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com