以下是我的Angular 5应用程序的简化版本。我有一个reducer,我想在我的root模块中注册。在 LINE A 中,我收到以下错误:
ERROR in src/app/store/app.reducers.ts(7,14): error TS2322: Type '{ post: (state: State, action: Action) => void; }' is not assignable to type 'ActionReducerMap<AppState, Action>'.
Types of property 'post' are incompatible.
Type '(state: State, action: Action) => void' is not assignable to type 'ActionReducer<State, Action>'.
Type 'void' is not assignable to type 'State'.
app.module.ts :根模块
imports: [
...
StoreModule.forRoot(reducers)
],
store / app.reducers.ts :在全球商店内
import {ActionReducerMap} from "@ngrx/store";
import * as fromPost from "../postDir/store/post.reducers";
export interface AppState {
post:fromPost.State
}
export const reducers: ActionReducerMap<AppState> = { //=======LINE A ======
post:fromPost.postReducer
};
postDir / store / post.reducers.ts :在本地商店内
export interface State{
query:string
posts:Post[]
}
const initialPostState: State = {
query:"initial",
posts:[]
};
export function postReducer(state = initialPostState, action:postActions.PostActions){}
如果我将 LINE A 中的<AppState>
替换为<any>
,则代码可以正常工作
有没有其他人面临类似的问题?我试图谷歌,但找不到任何重要的东西。
答案 0 :(得分:4)
您的错误消息显示属性post
具有错误的方法签名。它是(state: State, action: Action) => void
但应该是(state: State, action: Action) => State
。在post.reducers.ts
中,您的reducer需要返回传递给它的状态,如下所示:export function postReducer(state = initialPostState, action:Action){ return state; };
。返回类型是从您的内容中隐式推断出来的,或者在这种情况下不会返回。您可以使用...): State {...
显式声明返回类型,但仍应返回状态。
答案 1 :(得分:0)
我遇到了类似的情况,经过很多时间,检查我的代码,我发现在reducer的switch case操作中缺少属性返回。
确保使用扩展运算符...state
加载以前的状态,从而避免了很多难以发现的问题。在我的情况下,我返回了所有属性,但没有先加载先前状态的属性。遇到TS2322错误,花费了数小时来修复和了解发生了什么。
以您的代码为例:
export function postReducer(state = initialPostState, action:postActions.PostActions){
// here you must return the state after an action
switch (action.type){
case postActions.ACTION_EXAMPLE:
return {
...state, someProperty: action.payload // here you load your previous state and change just that one you want
}
case postActions.ACTION_02_EXAMPLE:
return {
...state, someProperty: action.payload // here you load your previous state and change just that one you want
}
default:
return { ...state}
}
}
希望有帮助!
答案 2 :(得分:0)
回答是否有人偶然发现了与我相同的错误。我想通过特定操作将状态重置为初始状态时,使用@ngrx/entity
遇到此问题。我有
我有
on(actions.resetState, () => adapter.getInitialState())
当我应该拥有额外的属性时,例如
on(actions.resetState, () => adapter.getInitialState({ foo: 'bar' }))