我遇到此类型错误,该错误使用带有typescript的react-redux破坏了应用程序。
错误:
这来自创建我的商店的root_store.ts
文件:
const persistConfig = {
key: 'root',
storage
};
const persistedReducer = persistReducer(persistConfig, rootReducer);
const configureStore = () => {
const middlewares = [thunk];
const middlewareEnhancer = applyMiddleware(...middlewares);
const enhancers = [middlewareEnhancer];
const composedEnhancers = composeWithDevTools(...enhancers);
const store = createStore(persistedReducer, composedEnhancers);
const peristor = persistStore(store);
return { store, peristor };
};
export const { store, peristor } = configureStore();
和我的根减速器上。我有这段代码。
export const rootReducer = combineReducers({
user
});
export type RootState = ReturnType<typeof rootReducer>;
如果我从combineReducers fn
中删除类型,例如combineReducer<AppState>
,则会出现我不知道为什么的错误。
这是用户减速器的代码:
const user = (state = userInitialState, action: UserActionTypes): IUser => {
switch (action.type) {
case UserEnumTypes.USER_INFO: {
return {
...state,
...action.payload
};
}
case UserEnumTypes.USER_LOGOUT: {
return {
...state,
...action.payload
};
}
default: {
return state;
}
}
};
export default user;
此处是用户操作的代码
export const setupUserOnSuccessLoginORSignup = (user: IUser): ISetupUserOnSuccessLoginORSignup => ({
type: UserEnumTypes.USER_INFO,
payload: {
...user
}
});
export const logoutUser = (): ILogoutUser => ({
type: UserEnumTypes.USER_LOGOUT,
payload: {
...userInitialState
}
});
以下是用户的操作类型:
export enum UserEnumTypes {
USER_INFO = 'USER_INFO',
USER_LOGOUT = 'USER_LOGOUT'
}
export interface ISetupUserOnSuccessLoginORSignup {
type: typeof UserEnumTypes.USER_INFO;
payload: {
id: number | null;
username: string;
email: string;
createdAt?: string;
updatedAt?: string;
usersGameGroups?: IUsersGameGroup[];
posts?: IPost[];
};
}
export interface ILogoutUser {
type: typeof UserEnumTypes.USER_LOGOUT;
payload: {
id: number | null;
username: string;
email: string;
};
}
export type UserActionTypes = ISetupUserOnSuccessLoginORSignup | ILogoutUser;
我在redux指南 https://redux.js.org/recipes/usage-with-typescript#type-checking-reducers
中遵循了此步骤并阅读相反的问题。 Typescript: How to type combined reducers?
虽然很奇怪,因为他没有导出CombineReducers,但也许他将其保存在单个文件中。
我想在any
中添加const store:any = createStore(persistedReducer, composedEnhancers);
类型,这可以解决错误,但是建议这样做,我担心的是,当我将props映射到组件时,我会丢失类型检查吗?